150个Java面试问答-最终清单(PDF下载)
我們的Java面試問題和答案集合全都涉及可以在Java面試中使用的不同類型的問題,以使雇主可以測試您在Java和面向?qū)ο缶幊谭矫娴募寄堋?
在以下各節(jié)中,我們將討論有關(guān)面向?qū)ο缶幊碳捌涮匦缘腏ava面試問題,有關(guān)Java及其功能的一般問題,Java中的集合,垃圾收集器,異常處理,Java小程序,Swing,JDBC,遠程方法調(diào)用(RMI) ,Servlet和JSP。
我們走吧…!
目錄
面向?qū)ο缶幊?#xff08;OOP) B.關(guān)于Java的一般問題 C.Java線程 D.Java集合 E.垃圾收集器 F.異常處理 G.Java小程序 Swing JDBC J.遠程方法調(diào)用(RMI) Servlet JSPA.面向?qū)ο缶幊?#xff08;OOP)
1.什么是Java?
Java是一種并發(fā),基于類和面向?qū)ο蟮挠嬎銠C編程語言。 面向?qū)ο筌浖_發(fā)的優(yōu)勢如下所示:
- 代碼的模塊化開發(fā),使維護和修改變得容易。
- 代碼的可重用性。
- 提高了代碼的可靠性和靈活性。
- 增加了對代碼的理解。
2. OOP的概念是什么?
面向?qū)ο缶幊?#xff08;OOP)包括:
- 抽象化
- 封裝形式
- 多態(tài)性
- 遺產(chǎn)
- 預(yù)定義類型必須是對象
- 用戶定義的類型必須是對象
- 必須通過向?qū)ο蟀l(fā)送消息來執(zhí)行操作
3.提及Java的某些功能
在Java的普及中起重要作用的一些功能如下:
- 面向?qū)ο?
- 平臺無關(guān)
- 高性能
- 多線程
- 隨身攜帶
- 安全
Java中的Helloworld的示例代碼如下所示:
你好,世界
public class Helloworld{public static void main(String args[]) { System.out.println("Hello World"); } }4. Java 100%是面向?qū)ο蟮膯?#xff1f;
不是100%。 Java不能滿足所有的OOP條件(預(yù)定義類型必須是對象),因為它使用了不是對象的八種原始數(shù)據(jù)類型(布爾,字節(jié),字符,整數(shù),浮點,雙精度,長,短)。
5.什么是抽象?
抽象是將思想與特定實例分離開來的過程,因此根據(jù)其自身的功能而不是其實現(xiàn)細節(jié)來開發(fā)類。 Java支持公開接口的抽象類的創(chuàng)建和存在,而不包括所有方法的實際實現(xiàn)。 抽象技術(shù)旨在將類的實現(xiàn)細節(jié)與其行為分開。
下面介紹了抽象類Person。 它具有抽象方法getName。
抽象類人
public abstract class Person { public abstract String getName(); }Employee類擴展了Abstract類Person。 方法getName返回雇員的name屬性。
員工階層
public class Employee extends Person { private String name;public Employee(String name){this.name = name;}public String getName(){return this.name;}public static void main (String args[]) { Employee employee = new Employee("John Wilson");System.out.println("Employee's Name "+ employee.getName()); Person person = new Employee("Thomas Smith");System.out.println("Employee-Person's Name "+ person.getName());} }6.什么是封裝?
封裝使對象能夠隱藏其內(nèi)部特征和行為。 每個對象提供許多方法,其他對象可以訪問這些方法并更改其內(nèi)部數(shù)據(jù)。 在Java中,有三種訪問修飾符:public,private和protected。 每個修飾符都對相同或外部軟件包中的其他類施加不同的訪問權(quán)限。 下面列出了使用封裝的一些優(yōu)點:
- 隱藏每個對象的屬性可以保護每個對象的內(nèi)部狀態(tài)。
- 因為可以獨立更改或擴展對象的行為,所以它增加了代碼的可用性和維護。
- 它通過防止對象以不希望的方式相互交互來提高模塊化。
您可以在此處參考我們的教程,以獲取有關(guān)封裝的更多詳細信息和示例。
帶有屬性Id和Name的樣本類Student被顯示為封裝示例。
學(xué)生班
public class Student{ private int id; private String name; public void setId(int id){this.id = id;}public void setName(String name){this.name = name;}public int getId(){return this.id;}public String getName(){return this.name;}public static void main(String args[]) { Student student=new Student(); student.setId(1034);student.setName("David Smith");System.out.println("Student id "+ student.getId());System.out.println("Student name "+ student.getName());} }7.抽象和封裝之間有什么區(qū)別?
抽象和封裝是互補的概念。 一方面,抽象集中于對象的行為。 另一方面,封裝著重于對象行為的實現(xiàn)。 封裝通常是通過隱藏有關(guān)對象內(nèi)部狀態(tài)的信息來實現(xiàn)的,因此可以看作是用于提供抽象的策略。
8.什么是多態(tài)?
多態(tài)是編程語言為不同的基礎(chǔ)數(shù)據(jù)類型提供相同接口的能力。 多態(tài)類型是一種類型,其操作也可以應(yīng)用于其他類型的值。
您可以在下面的示例中看到“車輛”界面具有方法“ invokeVelocity”。 卡車,火車和飛機實現(xiàn)了車輛界面,并且該方法將速度增加到與車輛類型相關(guān)的適當(dāng)速度。
多態(tài)性9.多態(tài)性有哪些類型?
Java中有兩種類型的多態(tài)性:
- 編譯時多態(tài)(靜態(tài)綁定)–方法重載
- 運行時多態(tài)(動態(tài)綁定)–方法覆蓋
我們可以通過方法重載和方法重載來執(zhí)行多態(tài)。
| 編譯時間 | 運行 |
| 類的方法具有相同的名稱。 每種方法都有不同數(shù)量的參數(shù)。 它可以具有不同類型和順序的參數(shù)。 | 子類具有名稱與超類方法相同的方法。 它具有超類方法的參數(shù)數(shù)量,參數(shù)類型和返回類型。 |
| 方法重載是要增加方法的行為。 它可以擴展到方法的行為。 | 方法重寫是修改方法的行為。 |
| 重載的方法將沒有相同的簽名。 | 重寫的方法將具有完全相同的簽名。 |
| 在這種情況下,不需要繼承。 | 繼承是必需的。 |
計算器類的重載方法減去的示例代碼如下所示:
計算器類
public class Calculator {public int subtract(int a, int b) {return a-b; } public double subtract( double a, double b) {return a-b; }public static void main(String args[]) {Calculator calculator = new Calculator();System.out.println("Difference of 150 and 12 is " +calculator.subtract(150,12));System.out.println("Difference of 15.5 and 15.4 is " +calculator.subtract(15.50,15.40)); }}方法覆蓋在Shape類中顯示。 Shape有一個方法getArea。
形狀等級
public class Shape { public void getArea(){System.out.println("Shape Area");} }Rectangle類重寫getArea方法,并且該方法的實現(xiàn)特定于Rectangle。 覆蓋注釋用于向編譯器指示該方法被覆蓋。 使用注釋可以提高代碼的可讀性。
矩形類
public class Rectangle extends Shape{ @Overridepublic void getArea(){System.out.println("Rectangle Area");} public static void main(String args[]){ Shape shape = new Shape();shape.getArea();Rectangle rectangle = new Rectangle(); rectangle.getArea(); } }10.什么是繼承?
繼承為對象提供了獲取另一個類(稱為基類)的字段和方法的能力。 繼承提供了代碼的可重用性,并且可以用于繼承現(xiàn)有類,而無需對其進行修改。
下面顯示的示例類Mammal具有一個構(gòu)造函數(shù)。
哺乳動物類
public class Mammal{ public Mammal(){System.out.println("Mammal created"); }}Man類擴展了具有默認構(gòu)造函數(shù)的Mammal。 示例代碼如下所示。
男子班
public class Man extends Mammal{ public Man(){ System.out.println("Man is created"); } }通過使用默認構(gòu)造函數(shù)創(chuàng)建Man的實例來測試繼承。 示例代碼顯示為演示繼承。
TestInheritance類
public class TestInheritance{public static void main(String args[]) { Man man = new Man(); } }11.什么是成分?
除了“部分”的生命周期由“整體”控制之外, 組成與“聚集”完全相同。 此控件可以是直接的或傳遞的。 也就是說,“整個”可能直接負責(zé)創(chuàng)建或銷毀“零件”,或者可以接受已經(jīng)創(chuàng)建的零件,然后將其傳遞給承擔(dān)此責(zé)任的其他整體。
下圖顯示了“汽車”示例類,以演示輪胎,門,窗和轉(zhuǎn)向的組成。
車類
public class Car { private Tire[] tires;private Door[] doors;private Steering steering;private Window[] windows; }class Tire {}class Door {}class Steering {}class Window {}12.什么是協(xié)會?
關(guān)聯(lián)表示一個實例向另一個實例發(fā)送消息的能力。 盡管通常也可以將其實現(xiàn)為方法自變量或創(chuàng)建局部變量,但通常使用指針或引用實例變量來實現(xiàn)。
13.什么是聚合?
聚集是典型的整體/部分關(guān)系。 這與關(guān)聯(lián)完全相同,但實例不能具有循環(huán)聚合關(guān)系。
下面顯示了示例類Person,以演示與Address的聚合關(guān)系。
人類
public class Person { private Address address;}class Address {private String city;private String state;private String country;private String line1;private String line2;}B.關(guān)于Java的一般問題
14.什么是JVM?
Java虛擬機(JVM)是??可以執(zhí)行Java 字節(jié)碼的進程虛擬機 。 每個Java源文件都被編譯為字節(jié)碼文件,該文件由JVM執(zhí)行。
15. Java為什么稱為平臺獨立編程語言?
Java旨在允許構(gòu)建可以在任何平臺上運行的應(yīng)用程序,而不必由程序員針對每個單獨的平臺進行重寫或重新編譯。 Java虛擬機使之成為可能,因為它知道特定的指令長度和底層硬件平臺的其他特殊性。
16. JDK和JRE有什么區(qū)別?
Java運行時環(huán)境(JRE)基本上是執(zhí)行Java程序的Java虛擬機(JVM)。 它還包括用于執(zhí)行applet的瀏覽器插件。 Java開發(fā)工具包(JDK)是用于Java的功能齊全的軟件開發(fā)工具包,包括JRE,編譯器和工具(如JavaDoc和Java Debugger ),以便用戶開發(fā),編譯和執(zhí)行Java應(yīng)用程序。
| JDK | 杰瑞 |
| JDK代表術(shù)語:Java開發(fā)工具包。 | JRE代表術(shù)語:Java運行時環(huán)境。 |
| JDK是用于編譯,記錄和打包Java軟件的工具。 | JRE是運行時環(huán)境。 JavaByte代碼在環(huán)境中執(zhí)行。 |
| JDK具有JRE和開發(fā)工具。 | JRE是JVM實現(xiàn) |
17. static關(guān)鍵字是什么意思?
static關(guān)鍵字表示可以訪問成員變量或方法,而無需實例化其所屬的類。
靜態(tài)方法示例如下所示:
靜態(tài)方法
static void printGreeting() {}18.您可以在Java中覆蓋私有方法還是靜態(tài)方法?
用戶無法覆蓋Java中的靜態(tài)方法 ,因為方法覆蓋基于運行時的動態(tài)綁定,而靜態(tài)方法是在編譯時靜態(tài)綁定的。 靜態(tài)方法未與類的任何實例相關(guān)聯(lián),因此該概念不適用。
19.您可以在靜態(tài)上下文中訪問非靜態(tài)變量嗎?
Java中的靜態(tài)變量屬于其類,并且其所有實例的值都相同。 JVM加載類時,將初始化靜態(tài)變量。 如果您的代碼試圖在沒有任何實例的情況下訪問非靜態(tài)變量,則編譯器會抱怨,因為這些變量尚未創(chuàng)建并且它們與任何實例都沒有關(guān)聯(lián)。
20. Java支持哪些數(shù)據(jù)類型?
Java編程語言支持的八種原始數(shù)據(jù)類型是:
- 字節(jié)
- 短
- 整型
- 長
- 浮動
- 雙
- 布爾值
- 燒焦
21.什么是自動裝箱和拆箱?
自動裝箱是Java編譯器在原始類型及其對應(yīng)的對象包裝器類之間進行的自動轉(zhuǎn)換 。 例如,編譯器將int轉(zhuǎn)換為Integer ,將double轉(zhuǎn)換為Double ,依此類推。 如果轉(zhuǎn)換為其他方式,則此操作稱為拆箱。
22.什么是Java中的函數(shù)覆蓋和重載?
當(dāng)同一類中的兩個或多個方法具有完全相同的名稱,但參數(shù)不同時,就會發(fā)生Java中的方法重載。 另一方面,方法覆蓋定義為子類重新定義與父類相同的方法時的情況。 重寫的方法必須具有相同的名稱,參數(shù)列表和返回類型。 覆蓋方法可能不會限制對其覆蓋的方法的訪問。
23.什么是構(gòu)造函數(shù)?
創(chuàng)建新對象時,將調(diào)用構(gòu)造函數(shù)。 每個類都有一個構(gòu)造函數(shù) 。 如果程序員沒有為類提供構(gòu)造函數(shù),則Java編譯器(Javac)為該類創(chuàng)建一個默認構(gòu)造函數(shù)。
下例顯示了Java中的默認構(gòu)造函數(shù):
默認構(gòu)造函數(shù)
public Man(){ System.out.println("Man is created"); }以下示例顯示了采用參數(shù)的構(gòu)造函數(shù):
建設(shè)者
private String name;public Employee(String name){this.name = name;}24.什么是構(gòu)造函數(shù)重載?
構(gòu)造函數(shù)重載類似于Java中的方法重載。 可以為單個類創(chuàng)建不同的構(gòu)造函數(shù)。 每個構(gòu)造函數(shù)必須具有自己的唯一參數(shù)列表。
25.什么是復(fù)制構(gòu)造函數(shù)?
最后,Java確實支持像C ++這樣的副本構(gòu)造函數(shù),但是不同之處在于,如果您不編寫自己的副本,則Java不會創(chuàng)建默認的副本構(gòu)造函數(shù)。
Employee類的復(fù)制構(gòu)造函數(shù)如下所示:
復(fù)制構(gòu)造函數(shù)
public class Employee extends Person { private String name;public Employee(String name){this.name = name;}public Employee(Employee emp){this.name = emp.name;}}26. Java是否支持多重繼承?
不,Java不支持多重繼承。 每個類只能在一個類上擴展,但可以實現(xiàn)多個接口。
多重繼承27.接口和抽象類有什么區(qū)別?
Java提供并支持抽象類和接口的創(chuàng)建。 兩種實現(xiàn)都有一些共同的特征,但是它們在以下特征上有所不同:
- 接口中的所有方法都是隱式抽象的。 另一方面,抽象類可能同時包含抽象方法和非抽象方法。
- 一個類可以實現(xiàn)許多接口,但只能擴展一個抽象類。
- 為了使類實現(xiàn)接口,它必須實現(xiàn)其所有聲明的方法。 但是,一個類可能無法實現(xiàn)抽象類的所有已聲明方法。 但是,在這種情況下,子類也必須聲明為抽象。
- 抽象類可以實現(xiàn)接口,甚至不提供接口方法的實現(xiàn)。
- 在Java接口中聲明的變量默認為final。 抽象類可能包含非最終變量。
- 默認情況下,Java接口的成員是公共的。 抽象類的成員可以是私有的,受保護的或公共的。
- 接口絕對是抽象的,無法實例化。 如果抽象類包含main方法,則它也不能實例化,但可以被調(diào)用。
另外,請查看JDK 8的Abstract類和接口的區(qū)別 。
| 接口 | 抽象類 |
| 接口具有方法簽名。 它沒有任何實現(xiàn)。 | 抽象類具有要覆蓋的抽象方法和細節(jié)。 |
| 一個類可以實現(xiàn)多個接口 | 在這種情況下,一個類只能擴展一個抽象類 |
| 接口具有所有抽象方法。 | 非抽象方法可以存在于抽象類中。 |
| 接口中不能存在實例屬性。 | 實例屬性可以存在于抽象類中。 |
| 接口是公開可見的還是不可見的。 | 抽象類可以是公共的,私有的和受保護的可見性。 |
| 接口中的任何更改都會影響實現(xiàn)該接口的類。 | 將方法添加到抽象類并實現(xiàn)它不需要更改派生類的代碼。 |
| 接口不能具有構(gòu)造函數(shù) | 抽象類可以具有構(gòu)造函數(shù) |
| 接口在性能方面很慢 | 抽象類可以快速執(zhí)行派生類中的方法。 |
28.什么是參考傳遞和價值傳遞?
通過值傳遞對象時,這意味著傳遞對象的副本。 因此,即使對該對象進行了更改,它也不會影響原始值。 通過引用傳遞對象時,這意味著不傳遞實際對象,而是傳遞該對象的引用。 因此,外部方法所做的任何更改也都會反映在所有地方。
下面提供了示例代碼,其中顯示了按值傳遞。
價值傳遞
public class ComputingEngine { public static void main(String[] args) { int x = 15;ComputingEngine engine = new ComputingEngine();engine.modify(x); System.out.println("The value of x after passing by value "+x); } public void modify(int x) { x = 12; } }下面的示例顯示了代碼中的引用傳遞。
通過參考
public class ComputingEngine { public static void main(String[] args) { ComputingEngine engine = new ComputingEngine();Computation computation = new Computation(65);engine.changeComputedValue(computation);System.out.println("The value of x after passing by reference "+ computation.x);} public void changeComputedValue(Computation computation){computation = new Computation();computation.x = 40;} }class Computation { int x; Computation(int i) { x = i; } Computation() { x = 1; } }29.易變變量的目的是什么?
易失性變量的值可以通過不同的線程進行修改。 他們將永遠沒有機會阻止并保持鎖。 只要訪問變量,就會發(fā)生同步。 使用volatile可能比使用鎖快,但在某些情況下將不起作用。 Java 5擴展了volatile有效的情況范圍; 特別是,雙重檢查鎖定現(xiàn)在可以正常工作。
volatile變量的示例代碼如下所示:
揮發(fā)性變量
public class DistributedObject {public volatile int count = 0;}30.瞬時變量的目的是什么?
即使將瞬態(tài)變量所屬的類進行了序列化,也不會對其進行序列化。
具有瞬態(tài)變量的示例類如下所示:
暫時變量
public class Paper implements Serializable {private int id;private String title;private String author;private transient int version = 1;}31.什么是局部變量和實例變量?
| 局部變量 | 實例變量 |
| 局部變量在方法或構(gòu)造函數(shù)中聲明。 可以在一個塊中聲明 | 實例變量在類內(nèi)聲明。 |
| 使用前需要初始化局部變量。 該代碼將無法編譯。 | 實例變量初始化不是必需的。 如果未初始化,則使用默認值。 |
32. Java中有哪些不同的訪問修飾符?
有四種類型的訪問修飾符:
- 公開-可從應(yīng)用程序中的任何地方訪問
- 受保護–可在包中以及任何包中的子類中訪問
- 包私有(默認)–只能在包內(nèi)訪問
- 私有–僅在聲明它的同一個類中可以訪問
33.靜態(tài)綁定和動態(tài)綁定之間的區(qū)別
| 靜態(tài)綁定 | 動態(tài)綁定 |
| 過程的定義與靜態(tài)綁定有關(guān) | 動態(tài)綁定的一個示例是過程的激活 |
| 聲明變量名稱是為了靜態(tài)綁定變量。 | 名稱的綁定可以是動態(tài)綁定。 |
| 聲明的范圍是靜態(tài)綁定的。 | 綁定的生命周期是動態(tài)綁定的。 |
靜態(tài)綁定的示例代碼如下所示:
靜態(tài)綁定
public class Shape { public void getArea(){System.out.println("Shape Area");} public static void main(String args[]){ Shape shape = new Shape();shape.getArea();} }動態(tài)綁定的示例代碼如下所示:
動態(tài)綁定
public class Rectangle extends Shape{ public void getArea(){System.out.println("Rectangle Area");} public static void main(String args[]){ Shape shape = new Rectangle(); shape.getArea(); } }34.什么是包裝器類?
包裝器類將Java原語轉(zhuǎn)換為對象。 因此,原始包裝器類是一個包裝器類,它包裝,隱藏或包裝來自八個原始數(shù)據(jù)類型的數(shù)據(jù)類型,以便可以使用它們在另一個類或其他類中的方法來創(chuàng)建實例化的對象。 原始包裝器類可在Java API中找到。
35.什么是單身人士課,我們?nèi)绾问箚紊砣耸空n?
在單例課程中,我們:
- 確保僅存在單例類的一個實例
- 提供對該實例的全局訪問
要創(chuàng)建單例類,我們:
- 將該類的所有構(gòu)造函數(shù)聲明為私有
- 提供一個靜態(tài)方法,該方法返回對該實例的引用
下面的代碼示例顯示了Double Checked Singleton類的實現(xiàn)。
單身人士班
public class DoubleCheckedSingleton {private static volatile DoubleCheckedSingleton instance;public static DoubleCheckedSingleton getInstance() {if (instance == null) {synchronized (DoubleCheckedSingleton .class) {if (instance == null) {instance = new DoubleCheckedSingleton();}}}return instance;}}C.Java線程
36.進程和線程之間有什么區(qū)別?
進程是程序的執(zhí)行,而線程是進程內(nèi)的單個執(zhí)行序列。 一個進程可以包含多個線程。 線程有時稱為輕量級進程。
| Craft.io流程 | 線程數(shù) |
| 過程與程序的執(zhí)行有關(guān)。 | 進程由多個線程組成。 |
| 進程之間使用進程間通信進行通信。 | 進程的線程可以相互通信。 |
| 流程可以控制子流程。 | 進程的線程可以控制其他線程。 |
| 父進程中的任何修改都不會更改子進程 | 主線程中的任何修改都可能影響進程中其他線程的行為。 |
| 進程在單獨的內(nèi)存空間中執(zhí)行。 | 線程在共享內(nèi)存空間中執(zhí)行。 |
| 操作系統(tǒng)控制過程。 | 軟件開發(fā)人員可以控制線程的使用。 |
| 流程彼此獨立。 | 線程彼此依賴。 |
您想要哪一個,為什么?
可以使用三種方法來創(chuàng)建線程:
- 一個類可以擴展Thread類。
- 一個類可以實現(xiàn)Runnable接口。
- 應(yīng)用程序可以使用Executor框架來創(chuàng)建線程池。
首選Runnable接口,因為它不需要對象來繼承Thread類。 如果您的應(yīng)用程序設(shè)計需要多重繼承,則只有接口可以為您提供幫助。 而且,線程池非常有效,可以非常容易地實現(xiàn)和使用。
38.從高層次解釋可用線程狀態(tài)。
在執(zhí)行期間,線程可以處于以下狀態(tài)之一 :
- NEW :線程準備就緒,可以運行,但不一定立即開始運行。
- RUNNABLE :Java虛擬機(JVM)正在主動執(zhí)行線程的代碼。
- BLOCKED :線程處于阻塞狀態(tài),同時等待監(jiān)視器鎖。
- 等待 :線程等待另一個線程執(zhí)行特定操作。
- TIMED_WAITING :線程等待另一個線程執(zhí)行特定操作,直到指定的等待時間。
- 終止 :線程已完成執(zhí)行。
39.同步的方法和塊之間有什么區(qū)別?
在Java編程中,每個對象都有一個鎖。 線程可以通過使用synced關(guān)鍵字來獲取對象的鎖。 可以在方法級別(粗粒度鎖定)或代碼塊級別(細粒度鎖定)中應(yīng)用synced關(guān)鍵字。
40.監(jiān)視器內(nèi)部如何進行線程同步?
JVM將鎖與監(jiān)視器結(jié)合使用。 監(jiān)視器基本上是監(jiān)視一系列同步代碼并確保一次僅一個線程執(zhí)行同步代碼段的監(jiān)護人。 每個監(jiān)視器都與一個對象引用關(guān)聯(lián)。 線程獲得鎖之前,不允許執(zhí)行代碼。
41.什么是僵局?
在繼續(xù)進行之前, 兩個進程互相等待完成的情況 。 結(jié)果是兩個進程都無限等待。
42.如何確保N個線程可以無死鎖地訪問N個資源?
在使用N個線程時避免死鎖的一種非常簡單的方法是在鎖上施加一個順序,并強制每個線程遵循該順序。 因此,如果所有線程以相同順序鎖定和解鎖互斥鎖,則不會出現(xiàn)死鎖。
43. Java中的wait和sleep方法有什么區(qū)別?
| 等待 | 睡覺 | |
| 呼吁 | 當(dāng)對象上有調(diào)用時,當(dāng)前線程在鎖對象上同步。 | 線程調(diào)用發(fā)生在當(dāng)前正在執(zhí)行的線程上。 |
| 已同步 | 同步用于從多個線程訪問同一對象。 | 同步用于在多個線程的睡眠線程上進行睡眠。 |
| 保持鎖 | 釋放其他對象的鎖,以便有機會執(zhí)行 | 如果指定了超時或有人中斷,請保持鎖定至少t次。 |
| 喚醒條件 | 直到調(diào)用notify(),然后從對象調(diào)用notifyAll() | 直到至少時間到期或調(diào)用interrupt()。 |
| 用法 | 用于時間同步 | 用于多線程同步 |
D.Java集合
44. Java Collections Framework的基本接口是什么?
Java Collections Framework提供了一組精心設(shè)計的接口和類,這些接口和類支持對對象集合的操作。 Java Collections Framework中最基本的接口是:
- Collection ,代表一組稱為其元素的對象。
- Set ,這是一個不能包含重復(fù)元素的集合。
- List ,這是一個有序集合,可以包含重復(fù)元素。
- Map ,這是一個將鍵映射到值并且不能包含重復(fù)鍵的對象。
45.為什么Collection不擴展Cloneable和Serializable接口?
Collection接口指定稱為元素的對象組。 Collection的每個具體實現(xiàn)都可以選擇自己的方式來維護和排序其元素。 一些集合允許重復(fù)的鍵,而另一些集合則不允許。 在處理實際的實現(xiàn)時,克隆或序列化的語義和含義都會發(fā)揮作用。 因此,集合的具體實現(xiàn)應(yīng)決定如何克隆或序列化它們。
46.什么是迭代器?
Iterator接口提供了許多可以迭代任何Collection的方法 。 每個Java集合都包含返回Iterator實例的iterator方法。 迭代器能夠在迭代過程中從基礎(chǔ)集合中刪除元素 。
47. Iterator和ListIterator有什么區(qū)別?
這些元素的區(qū)別如下:
- 迭代器可用于遍歷Set和List集合,而ListIterator只能用于遍歷List。
- 迭代器只能在向前的方向上遍歷一個集合,而ListIterator可以在兩個方向上遍歷一個List。
- ListIterator實現(xiàn)Iterator接口,并包含其他功能,例如添加元素,替換元素,獲取上一個和下一個元素的索引位置等。
48.故障快速和故障安全之間有什么區(qū)別?
Iterator的故障安全屬性可與基礎(chǔ)集合的克隆一起使用,因此,不受集合中任何修改的影響。 java.util包中的所有收集類都是快速失敗的,而java.util.concurrent中的收集類則是故障安全的。 快速故障迭代器拋出ConcurrentModificationException ,而故障安全迭代器從不拋出此類異常。
49. HashMap如何在Java中工作?
Java中的HashMap存儲鍵值對 。 HashMap需要一個哈希函數(shù),并使用hashCode和equals方法,以便分別將元素放置到集合中或從集合中檢索元素。 調(diào)用put方法時,HashMap將計算鍵的哈希值,并將該對存儲在集合內(nèi)的適當(dāng)索引中。 如果鍵存在,則其值將用新值更新。 HashMap的一些重要特征是其容量,負載因子和調(diào)整閾值的大小。
50. hashCode()和equals()方法的重要性是什么?
在Java中, HashMap使用hashCode和equals方法確定鍵值對的索引并檢測重復(fù)項。 更具體地說,使用hashCode方法來確定指定密鑰的存儲位置。 由于不同的鍵可能會產(chǎn)生相同的哈希值,因此使用equals方法來確定指定鍵在集合中是否實際存在。 因此,兩種方法的實現(xiàn)對于HashMap的準確性和效率至關(guān)重要。
51. HashMap和Hashtable有什么區(qū)別?
HashMap和Hashtable類都實現(xiàn)Map接口,因此具有非常相似的特性。 但是,它們在以下功能方面有所不同:
- HashMap允許存在空鍵和值,而Hashtable既不允許空鍵也不允許空值。
- Hashtable是同步的,而HashMap不是同步的。 因此,在單線程環(huán)境中首選使用HashMap,而在多線程環(huán)境中使用Hashtable。
- HashMap提供其鍵集,Java應(yīng)用程序可以對其進行迭代。 因此,HashMap是快速失敗的。 另一方面,哈希表提供其鍵的枚舉 。
- Hashtable類被認為是舊類。
什么時候在ArrayList上使用Array?
Array和ArrayList類在以下功能上有所不同:
- 數(shù)組可以包含原語或?qū)ο?#xff0c;而ArrayList只能包含對象。
- 數(shù)組具有固定大小,而ArrayList是動態(tài)的。
- ArrayList提供更多的方法和功能,例如addAll , removeAll , iterator等等。
- 對于原始數(shù)據(jù)類型的列表,集合使用自動裝箱來減少編碼工作。 但是,這種方法使它們在處理固定大小的原始數(shù)據(jù)類型時速度較慢。
| 數(shù)組 | 數(shù)組列表 |
| 數(shù)組不應(yīng)具有不同數(shù)據(jù)類型的值 | 數(shù)組列表可以具有不同數(shù)據(jù)類型的值。 |
| 聲明時定義了錯誤的大小 | ArrayList的大小可以動態(tài)更改 |
| 您必須指定索引才能在數(shù)組中添加數(shù)據(jù) | 您不需要在ArrayList中指定索引 |
| 數(shù)組未參數(shù)化類型 | 可以對數(shù)組列表進行參數(shù)化。 |
| 數(shù)組可以具有原始數(shù)據(jù)類型以及對象 | 數(shù)組列表只能有對象,不允許使用原始數(shù)據(jù)類型 |
53. ArrayList和LinkedList有什么區(qū)別?
ArrayList和LinkedList類都實現(xiàn)List接口,但是它們在以下功能上有所不同:
- ArrayList是由Array支持的基于索引的數(shù)據(jù)結(jié)構(gòu)。 它提供對元素的隨機訪問,其性能等于O(1)。 另一方面,LinkedList將其數(shù)據(jù)存儲為元素列表,并且每個元素都鏈接到其上一個和下一個元素。 在這種情況下,元素的搜索操作的執(zhí)行時間等于O(n)。
- 與ArrayList相比,LinkedList中元素的插入,添加和刪除操作更快,因為在集合中任意位置添加元素時,無需調(diào)整數(shù)組大小或更新索引。
- LinkedList比ArrayList消耗更多的內(nèi)存,因為LinkedList中的每個節(jié)點都存儲兩個引用,一個引用用于其上一個元素,一個用于其下一個元素。
另請參閱我們的文章ArrayList與LinkedList 。
54.比較器和比較器有什么區(qū)別?
- Java提供了Comparable接口,該接口僅包含一種稱為compareTo的方法。 此方法比較兩個對象,以便在它們之間施加一個順序。 具體來說,它返回負整數(shù),零或正整數(shù),以指示輸入對象小于,等于或大于現(xiàn)有對象。
- Java提供了Comparator接口,其中包含兩個方法,稱為compare和equals 。 第一種方法比較其兩個輸入?yún)?shù),并在它們之間施加一個順序。 它返回負整數(shù),零或正整數(shù),以指示第一個參數(shù)小于,等于或大于第二個參數(shù)。 第二種方法需要一個對象作為參數(shù),目的是確定輸入對象是否等于比較器。 僅當(dāng)指定的對象也是比較器并且施加與該比較器相同的順序時,該方法才返回true。
55.什么是Java優(yōu)先級隊列?
PriorityQueue是一個無限制隊列,基于優(yōu)先級堆,并且其元素以其自然順序排序。 在創(chuàng)建它的時候,我們可以提供一個Comparator,它負責(zé)對PriorityQueue的元素進行排序。 PriorityQueue不允許null值 ,那些不提供自然順序的對象或那些沒有任何與之關(guān)聯(lián)的比較器的對象。 最后,Java PriorityQueue不是線程安全的,并且其入隊和出隊操作需要O(log(n))時間。
56.您對big-O表示法了解多少,并且可以舉出一些有關(guān)不同數(shù)據(jù)結(jié)構(gòu)的示例嗎?
Big-O符號只是描述了在數(shù)據(jù)結(jié)構(gòu)中元素數(shù)量增加時,算法在最壞情況下的伸縮性或性能。 Big-O表示法還可用于描述其他行為,例如內(nèi)存消耗。 由于收集類實際上是數(shù)據(jù)結(jié)構(gòu),因此我們通常使用Big-O表示法,根據(jù)時間,內(nèi)存和性能來選擇要使用的最佳實現(xiàn)。 Big-O表示法可以很好地說明大量數(shù)據(jù)的性能。
57.使用無序數(shù)組與有序數(shù)組之間的權(quán)衡是什么?
有序數(shù)組的主要優(yōu)點是,與無序數(shù)組的時間復(fù)雜度為O(n)相比,搜索時間的時間復(fù)雜度為O(log n)。 有序數(shù)組的缺點是插入操作的時間復(fù)雜度為O(n),因為必須移動具有較高值的??元素才能為新元素騰出空間。 取而代之的是,對無序數(shù)組的插入操作將花費O(1)的恒定時間。
58.與Java Collection框架相關(guān)的一些最佳實踐是什么?
- Choosing the right type of the collection to use, based on the application's needs, is very crucial for its performance. For example if the size of the elements is fixed and know a priori, we shall use an Array , instead of an ArrayList .
- Some collection classes allow us to specify their initial capacity. Thus, if we have an estimation on the number of elements that will be stored, we can use it to avoid rehashing or resizing.
- Always use Generics for type-safety, readability, and robustness. Also, by using Generics you avoid the ClassCastException during runtime.
- Use immutable classes provided by the Java Development Kit (JDK) as a key in a Map, in order to avoid the implementation of the hashCode and equals methods for our custom class.
- Program in terms of interface not implementation.
- Return zero-length collections or arrays as opposed to returning a null in case the underlying collection is actually empty.
59. What is the difference between Enumeration and Iterator interfaces?
Enumeration is twice as fast as compared to an Iterator and uses very less memory. However, the Iterator is much safer compared to Enumeration, because other threads are not able to modify the collection object that is currently traversed by the iterator. Also, Iterators allow the caller to remove elements from the underlying collection, something which is not possible with Enumerations.
60. What is the difference between HashSet and TreeSet?
The HashSet is Implemented using a hash table and thus, its elements are not ordered. The add, remove, and contains methods of a HashSet have constant time complexity O(1). On the other hand, a TreeSet is implemented using a tree structure. The elements in a TreeSet are sorted, and thus, the add, remove, and contains methods have time complexity of O(logn).
E.Garbage Collectors
61. What is the purpose of garbage collection in Java, and when is it used?
The purpose of garbage collection is to identify and discard those objects that are no longer needed by the application, in order for the resources to be reclaimed and reused.
62. What does System.gc() and Runtime.gc() methods do?
These methods can be used as a hint to the JVM, in order to start a garbage collection. However, this it is up to the Java Virtual Machine (JVM) to start the garbage collection immediately or later in time.
Sample class ReferenceObject is shown below to demonstrate the usage of System.gc and Runtime.gc methods.
public class ReferenceObject { public void finalize(){System.out.println("object is garbage collected");}public static void main(String args[]){ ReferenceObject refObj1=new ReferenceObject(); ReferenceObject refObj2=new ReferenceObject(); refObj1=null; refObj2=null; System.gc(); Runtime.gc(); } }63. When is the finalize() called? What is the purpose of finalization?
The finalize method is called by the garbage collector, just before releasing the object's memory. It is normally advised to release resources held by the object inside the finalize method.
Finalize method in ReferenceObject class is shown below as an example.
Finalize Method
public class ReferenceObject { public void finalize(){System.out.println("object is garbage collected");}}64. If an object reference is set to null, will the Garbage Collector immediately free the memory held by that object?
No, the object will be available for garbage collection in the next cycle of the garbage collector.
65. What is structure of Java Heap?
The JVM has a heap that is the runtime data area from which memory for all class instances and arrays is allocated. It is created at the JVM start-up. Heap memory for objects is reclaimed by an automatic memory management system which is known as a garbage collector. Heap memory consists of live and dead objects. Live objects are accessible by the application and will not be a subject of garbage collection. Dead objects are those which will never be accessible by the application, but have not been collected by the garbage collector yet. Such objects occupy the heap memory space until they are eventually collected by the garbage collector.
66. What is the difference between Serial and Throughput Garbage collector?
The throughput garbage collector uses a parallel version of the young generation collector and is meant to be used with applications that have medium to large data sets. On the other hand, the serial collector is usually adequate for most small applications (those requiring heaps of up to approximately 100MB on modern processors).
67. When does an Object becomes eligible for Garbage collection in Java?
A Java object is subject to garbage collection when it becomes unreachable to the program in which it is currently used.
68. Does Garbage collection occur in permanent generation space in JVM?
Garbage Collection does occur in PermGen space and if PermGen space is full or cross a threshold, it can trigger a full garbage collection. If you look carefully at the output of the garbage collector, you will find that PermGen space is also garbage collected. This is the reason why correct sizing of PermGen space is important to avoid frequent full garbage collections. Also check our article Java 8: PermGen to Metaspace .
F.Exception Handling
69. What are the differences between Checked Exception and Unchecked Exception?
| Checked Exception | Unchecked Exception |
| known as compile time exceptions | known as Runtime exceptions |
| propagated using throws keyword | automatically propagated |
| can create custom exception by extending java.lang.Exception class | can create custom exception by extending Runtime exception |
70. What is the difference between Exception and Error in java?
Exception and Error classes are both subclasses of the Throwable class. The Exception class is used for exceptional conditions that a user's program should catch. The Error class defines exceptions that are not expected to be caught by the user program.
71. What is the difference between throw and throws?
The throw keyword is used to explicitly raise a exception within the program. On the contrary, the throws clause is used to indicate those exceptions that are not handled by a method. Each method must explicitly specify which exceptions does not handle, so the callers of that method can guard against possible exceptions. Finally, multiple exceptions are separated by a comma.
| Throw | Throws |
| Throw is used for throwing an exception explicitly. | To declar an exception,throws is used. |
| Using throw only, Checked exceptions can not be propagated. | Using throws, Checked exception can be propagated. |
| Throw is always used with an instance. | Throws is always used with a class. |
| Throw is used inside the method. | Throws is used always with the method signature. |
| You should not throw multiple exception | You can declare multiple exceptions. |
72. What is the importance of finally block in exception handling?
A finally block will always be executed, whether or not an exception is actually thrown. Even in the case where the catch statement is missing and an exception is thrown, the finally block will still be executed. Last thing to mention is that the finally block is used to release resources like I/O buffers, database connections, etc.
Sample code below shows the finally block when exception is thrown.
Finally Block
public class DivideByZeroException { public static void main(String []args){ try{ int a = 1; System.out.println(a/0); }catch(Exception exception){System.out.println("exception is thrown");}finally { System.out.println("after the exception is handled"); } } }73. What will happen to the Exception object after exception handling?
The Exception object will be garbage collected in the next garbage collection.
74. What purpose does the keywords final, finally, and finalize fulfill?
- Final keyword is used to apply restrictions on class(immutable), method(cannot override) and variable(constant).
- Finally is a block that always executes when the try block exits even if an unexpected exception occurs.
- Finalize is a method called to clean or release the resources by the Garbage Collector before destroying the object.
G.Java Applets
75. What is an Applet?
A java applet is program that can be included in a HTML page and be executed in a java enabled client browser. Applets are used for creating dynamic and interactive web applications.
76. Explain the life cycle of an Applet.
An applet may undergo the following states:
- Init : An applet is initialized each time is loaded.
- Start : Begin the execution of an applet.
- Stop : Stop the execution of an applet.
- Destroy : Perform a final cleanup, before unloading the applet.
77. What happens when an applet is loaded?
First of all, an instance of the applet's controlling class is created. Then, the applet initializes itself and finally, it starts running.
78. What is the difference between an Applet and a Java Application?
Applets are executed within a java enabled browser, but a Java application is a standalone Java program that can be executed outside of a browser. However, they both require the existence of a Java Virtual Machine (JVM). Furthermore, a Java application requires a main method with a specific signature, in order to start its execution. Java applets do not need such a method to start their execution. Finally, Java applets typically use a restrictive security policy, while Java applications usually use more relaxed security policies.
79. What are the restrictions imposed on Java applets?
Mostly due to security reasons, the following restrictions are imposed on Java applets:
- An applet cannot load libraries or define native methods.
- An applet cannot ordinarily read or write files on the execution host.
- An applet cannot read certain system properties.
- An applet cannot make network connections except to the host that it came from.
- An applet cannot start any program on the host that is executing it.
80. What are untrusted applets?
Untrusted applets are those Java applets that cannot access or execute local system files. By default, all downloaded applets are considered as untrusted.
81. What is the difference between applets loaded over the internet and applets loaded via the file system?
Regarding the case where an applet is loaded over the internet, the applet is loaded by the applet classloader and is subject to the restrictions enforced by the applet security manager. Regarding the case where an applet is loaded from the client's local disk, the applet is loaded by the file system loader. Applets loaded via the file system are allowed to read files, write files and to load libraries on the client. Also, applets loaded via the file system are allowed to execute processes and finally, applets loaded via the file system are not passed through the byte code verifier.
82. What is the applet class loader, and what does it provide?
When an applet is loaded over the internet, the applet is loaded by the applet classloader. The class loader enforces the Java namespace hierarchy. Also, the class loader guarantees that a unique namespace exists for classes that come from the local file system, and that a unique namespace exists for each network source. When a browser loads an applet over the net, that applet's classes are placed in a private namespace associated with the applet's origin. Then, those classes loaded by the class loader are passed through the verifier. The verifier checks that the class file conforms to the Java language specification. Among other things, the verifier ensures that there are no stack overflows or underflows and that the parameters to all bytecode instructions are correct.
83. What is the applet security manager, and what does it provide?
The applet security manager is a mechanism to impose restrictions on Java applets. A browser may only have one security manager. The security manager is established at startup, and it cannot thereafter be replaced, overloaded, overridden, or extended.
H.Swing
84. What is the difference between a Choice and a List?
A Choice is displayed in a compact form that must be pulled down, in order for a user to be able to see the list of all available choices. Only one item may be selected from a Choice. A List may be displayed in such a way that several List items are visible. A List supports the selection of one or more List items.
85. What is a layout manager?
A layout manager is the used to organize the components in a container.
86. What is the difference between a Scrollbar and a JScrollPane?
A Scrollbar is a Component , but not a Container . A ScrollPane is a Container. A ScrollPane handles its own events and performs its own scrolling.
87. Which Swing methods are thread-safe?
There are only three thread-safe methods: repaint, revalidate, and invalidate.
88. Name three Component subclasses that support painting.
The Canvas , Frame , Panel , and Applet classes support painting.
89. What is clipping?
Clipping is defined as the process of confining paint operations to a limited area or shape.
90. What is the difference between a MenuItem and a CheckboxMenuItem?
The CheckboxMenuItem class extends the MenuItem class and supports a menu item that may be either checked or unchecked.
91. How are the elements of a BorderLayout organized?
The elements of a BorderLayout are organized at the borders (North, South, East, and West) and the center of a container.
92. How are the elements of a GridBagLayout organized?
The elements of a GridBagLayout are organized according to a grid. The elements are of different sizes and may occupy more than one row or column of the grid. Thus, the rows and columns may have different sizes.
93. What is the difference between a Window and a Frame?
The Frame class extends the Window class and defines a main application window that can have a menu bar.
94. What is the relationship between clipping and repainting?
When a window is repainted by the AWT painting thread, it sets the clipping regions to the area of the window that requires repainting.
95. What is the relationship between an event-listener interface and an event-adapter class?
An event-listener interface defines the methods that must be implemented by an event handler for a particular event. An event adapter provides a default implementation of an event-listener interface.
96. How can a GUI component handle its own events?
A GUI component can handle its own events, by implementing the corresponding event-listener interface and adding itself as its own event listener.
97. What advantage do Java's layout managers provide over traditional windowing systems?
Java uses layout managers to lay out components in a consistent manner, across all windowing platforms. Since layout managers are not tied to absolute sizing and positioning, they are able to accomodate platform-specific differences among windowing systems.
98. What is the design pattern that Java uses for all Swing components?
The design pattern used by Java for all Swing components is the Model View Controller (MVC) pattern.
MVCI.JDBC
99. What is JDBC?
JDBC is an abstraction layer that allows users to choose between databases. JDBC enables developers to write database applications in Java , without having to concern themselves with the underlying details of a particular database.
100. What are the JDBC API components?
The java.sql package contains:
Interfaces :
- 司機
- 連接
- 聲明
- PreparedStatement
- CallableStatement
- ResultSet
Classes :
- DriverManager
- SQLException
101. Explain the role of Driver in JDBC.
The JDBC Driver provides vendor-specific implementations of the abstract classes provided by the JDBC API. Each driver must provide implementations for the following interfaces of the java.sql package: Connection , Statement , PreparedStatement , CallableStatement , ResultSet and Driver .
102. What is JDBC Connection interface?
Connection interface maintains a session with the database. SQL statements are executed and results are returned within the context of a connection. A Connection object's database is able to provide information describing its tables, its supported SQL grammar, its stored procedures, the capabilities of this connection, and so on. This information is obtained with the getMetaData method.
103. What does Connection pooling mean?
The interaction with a database can be costly, regarding the opening and closing of database connections. Especially, when the number of database clients increases, this cost is very high and a large number of resources is consumed.A pool of database connections is obtained at start up by the application server and is maintained in a pool. A request for a connection is served by a connection residing in the pool . In the end of the connection, the request is returned to the pool and can be used to satisfy future requests.
104. What is the role of JDBC DriverManager class?
The DriverManager provides the user with a basic service for managing a set of JDBC drivers. It maintains contact with the available drivers and establishes a database connection with an appropriate one.
105. What is the purpose Class.forName method?
This method is used to load the driver that will establish a connection to the database.
Sample Class ClassLoader is shown below to demonstrate the usage of Class.forName() method.
Class.forName
public class ClassLoader {public static void main(String[] args) {try {Class cls = Class.forName("BasicClass");.....System.out.println("Class = " + cls.getName());}catch(ClassNotFoundException exception) {System.out.println(exception.toString());}}106. What is the advantage of PreparedStatement over Statement?
PreparedStatement is precompiled and thus, performance is much better . Also, PreparedStatement objects can be reused with different input values to their queries.
107. What is the use of CallableStatement?
A CallableStatement is used to execute stored procedures. Stored procedures are stored and offered by a database. Stored procedures may take input values from the user and may return a result. The usage of stored procedures is highly encouraged, because it offers security and modularity.The method that prepares a CallableStatement is CallableStatement.prepareCall().
108. What do you mean by batch processing in JDBC?
Batch processing groups related SQL statements and execute multiple queries when the batch size reaches a desired threshold. This makes the performance faster.
J.Remote Method Invocation (RMI)
109. What is RMI?
The Java Remote Method Invocation (Java RMI) is a Java API that performs the object-oriented equivalent of remote procedure calls (RPC), with support for direct transfer of serialized Java classes and distributed garbage collection. Remote Method Invocation (RMI) can also be seen as the process of activating a method on a remotely running object. RMI offers location transparency because a user feels that a method is executed on a locally running object. Check some RMI Tips here .
110. What is the basic principle of RMI architecture?
The RMI architecture is based on a very important principle which states that the definition of the behavior and the implementation of that behavior, are separate concepts. RMI allows the code that defines the behavior and the code that implements the behavior to remain separate and to run on separate JVMs.
RMI Architecture111. What are the layers of RMI Architecture?
The RMI architecture consists of the following layers:
- Stub and Skeleton layer : This layer lies just beneath the view of the developer. This layer is responsible for intercepting method calls made by the client to the interface and redirect these calls to a remote RMI Service.
- Remote Reference Layer : The second layer of the RMI architecture deals with the interpretation of references made from the client to the server's remote objects. This layer interprets and manages references made from clients to the remote service objects. The connection is a one-to-one (unicast) link.
- Transport layer : This layer is responsible for connecting the two JVM participating in the service. This layer is based on TCP/IP connections between machines in a network. It provides basic connectivity, as well as some firewall penetration strategies.
112. What is the role of Remote Interface in RMI?
The Remote interface serves to identify interfaces whose methods may be invoked from a non-local virtual machine. Any object that is a remote object must directly or indirectly implement this interface. A class that implements a remote interface should declare the remote interfaces being implemented, define the constructor for each remote object and provide an implementation for each remote method in all remote interfaces.
113. What is the role of the java.rmi.Naming Class?
The java.rmi.Naming class provides methods for storing and obtaining references to remote objects in the remote object registry. Each method of the Naming class takes as one of its arguments a name that is a String in URL format.
114. What is meant by binding in RMI?
Binding is the process of associating or registering a name for a remote object, which can be used at a later time, in order to look up that remote object. A remote object can be associated with a name using the bind or rebind methods of the Naming class.
115. What is the difference between using bind() and rebind() methods of Naming Class?
The bind method bind is responsible for binding the specified name to a remote object, while the rebind method is responsible for rebinding the specified name to a new remote object. In case a binding exists for that name, the binding is replaced.
116. What are the steps involved to make work a RMI program?
The following steps must be involved in order for a RMI program to work properly:
- Compilation of all source files.
- Generation of the stubs using rmic.
- Start the rmiregistry.
- Start the RMIServer.
- Run the client program.
117. What is the role of stub in RMI?
A stub for a remote object acts as a client's local representative or proxy for the remote object. The caller invokes a method on the local stub, which is responsible for executing the method on the remote object. When a stub's method is invoked, it undergoes the following steps:
- It initiates a connection to the remote JVM containing the remote object.
- It marshals the parameters to the remote JVM.
- It waits for the result of the method invocation and execution.
- It unmarshals the return value or an exception if the method has not been successfully executed.
- It returns the value to the caller.
118. What is DGC and how does it work?
DGC stands for Distributed Garbage Collection. Remote Method Invocation (RMI) uses DGC for automatic garbage collection. Since RMI involves remote object references across JVMs, garbage collection can be quite difficult. DGC uses a reference counting algorithm to provide automatic memory management for remote objects.
119. What is the purpose of using RMISecurityManager in RMI?
RMISecurityManager provides a security manager that can be used by RMI applications, which use downloaded code. The class loader of RMI will not download any classes from remote locations, if the security manager has not been set.
120. Explain Marshalling and demarshalling.
When an application wants to pass its memory objects across a network to another host or persist it to storage, the in-memory representation must be converted to a suitable format. This process is called marshalling and the revert operation is called demarshalling.
121. Explain Serialization and Deserialization.
Java provides a mechanism, called object serialization where an object can be represented as a sequence of bytes and includes the object's data, as well as information about the object's type, and the types of data stored in the object. Thus, serialization can be seen as a way of flattening objects, in order to be stored on disk, and later, read back and reconstituted. Deserialisation is the reverse process of converting an object from its flattened state to a live object.
K.Servlets
122. What is a Servlet?
The servlet is a Java programming language class used to process client requests and generate dynamic web content. Servlets are mostly used to process or store data submitted by an HTML form, provide dynamic content and manage state information that does not exist in the stateless HTTP protocol.
123. Explain the architecture of a Servlet.
The core abstraction that must be implemented by all servlets is the javax.servlet.Servlet interface. Each servlet must implement it either directly or indirectly, either by extending javax.servlet.GenericServlet or javax.servlet.http.HTTPServlet. Finally, each servlet is able to serve multiple requests in parallel using multithreading.
Servlet Architecture124. What is the difference between an Applet and a Servlet?
An Applet is a client side java program that runs within a Web browser on the client machine. On the other hand, a servlet is a server side component that runs on the web server.An applet can use the user interface classes, while a servlet does not have a user interface. Instead, a servlet waits for client's HTTP requests and generates a response in every request.
125. What is the difference between GenericServlet and HttpServlet?
GenericServlet is a generalized and protocol-independent servlet that implements the Servlet and ServletConfig interfaces. Those servlets extending the GenericServlet class shall override the service method. Finally, in order to develop an HTTP servlet for use on the Web that serves requests using the HTTP protocol, your servlet must extend the HttpServlet instead. Check Servlet examples here .
126. Explain the life cycle of a Servlet.
On every client's request, the Servlet Engine loads the servlets and invokes its init methods, in order for the servlet to be initialized. Then, the Servlet object handles all subsequent requests coming from that client, by invoking the service method for each request separately. Finally, the servlet is removed by calling the server's destroy method.
Servlet Lifecycle127. What is the difference between doGet() and doPost()?
doGET: The GET method appends the name-value pairs on the request's URL. Thus, there is a limit on the number of characters and subsequently on the number of values that can be used in a client's request. Furthermore, the values of the request are made visible and thus, sensitive information must not be passed in that way. doPOST: The POST method overcomes the limit imposed by the GET request, by sending the values of the request inside its body. Also, there is no limitations on the number of values to be sent across. Finally, the sensitive information passed through a POST request is not visible to an external client.
The code below shows the BasicServlet class which has doGet and doPost methods to be implemented.
Get and Post methods
public class BasicServlet extends HttpServlet {public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException{}public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException{} }128. What is meant by a Web Application?
A Web application is a dynamic extension of a Web or application server. There are two types of web applications: presentation-oriented and service-oriented. A presentation-oriented Web application generates interactive web pages, which contain various types of markup language and dynamic content in response to requests. On the other hand, a service-oriented web application implements the endpoint of a web service. In general, a Web application can be seen as a collection of servlets installed under a specific subset of the server's URL namespace.
129. What is a Server Side Include (SSI)?
Server Side Includes (SSI) is a simple interpreted server-side scripting language, used almost exclusively for the Web, and is embedded with a servlet tag. The most frequent use of SSI is to include the contents of one or more files into a Web page on a Web server. When a Web page is accessed by a browser, the Web server replaces the servlet tag in that Web page with the hyper text generated by the corresponding servlet.
130. What is Servlet Chaining?
Servlet Chaining is the method where the output of one servlet is sent to a second servlet. The output of the second servlet can be sent to a third servlet, and so on. The last servlet in the chain is responsible for sending the response to the client.
131. How do you find out what client machine is making a request to your servlet?
The ServletRequest class has functions for finding out the IP address or host name of the client machine. getRemoteAddr() gets the IP address of the client machine and getRemoteHost() gets the host name of the client machine. See example here .
132. What is the structure of the HTTP response?
The HTTP response consists of three parts:
- Status Code: describes the status of the response. It can be used to check if the request has been successfully completed. In case the request failed, the status code can be used to find out the reason behind the failure. If your servlet does not return a status code, the success status code, HttpServletResponse.SC_OK, is returned by default.
- HTTP Headers: they contain more information about the response. For example, the headers may specify the date/time after which the response is considered stale, or the form of encoding used to safely transfer the entity to the user. See how to retrieve headers in Servlet here .
- Body: it contains the content of the response. The body may contain HTML code, an image, etc. The body consists of the data bytes transmitted in an HTTP transaction message immediately following the headers.
133. What is a cookie?
A cookie is a bit of information that the Web server sends to the browser. The browser stores the cookies for each Web server in a local file. In a future request, the browser, along with the request, sends all stored cookies for that specific Web server.
134. What is the difference between session and cookie?
The differences between session and a cookie are the following:
- The session should work, regardless of the settings on the client browser. The client may have chosen to disable cookies. However, the sessions still work, as the client has no ability to disable them in the server side.
- The session and cookies also differ in the amount of information the can store. The HTTP session is capable of storing any Java object, while a cookie can only store String objects.
135. Which protocol will be used by browser and servlet to communicate?
The browser communicates with a servlet by using the HTTP protocol.
136. What is HTTP Tunneling?
HTTP Tunneling is a technique by which, communications performed using various network protocols are encapsulated using the HTTP or HTTPS protocols. The HTTP protocol therefore acts as a wrapper for a channel that the network protocol being tunneled uses to communicate. The masking of other protocol requests as HTTP requests is HTTP Tunneling.
137. What's the difference between sendRedirect and forward methods?
The sendRedirect method creates a new request, while the forward method just forwards a request to a new target. The previous request scope objects are not available after a redirect, because it results in a new request. On the other hand, the previous request scope objects are available after forwarding. FInally, in general, the sendRedirect method is considered to be slower compare to the forward method.
| SendRedirect | Forward |
| This method sends a new request always. Th is because it uses the URL bar of the browser for redirecting. | This method sends the request to another resource by forwarding it. |
| This method is used at client side. | This method is usead at server side. |
| This method is used inside and outside the web server. | This method is used inside the web server only. |
138. What is URL Encoding and URL Decoding?
The URL encoding procedure is responsible for replacing all the spaces and every other extra special character of a URL, into their corresponding Hex representation. In correspondence, URL decoding is the exact opposite procedure.
139. What is Request Dispatcher?
Servlet Request Dispatcher is an interface whose implementation defines that an object can dispatch requests to any resource (such as HTML, Image, JSP, Servlet etc.) on the server. Another advantage of this interface is that it is used in two cases:
- To include the response of one Servlet into another (ie the client gets the response of both Servlets)
- To forward the client request to another Servlet to honor the request (ie the client calls a Servlet but the response to client is given by another Servlet)
L.JSP
140. What is a JSP Page?
A Java Server Page ( JSP ) is a text document that contains two types of text: static data and JSP elements. Static data can be expressed in any text-based format, such as HTML or XML. JSP is a technology that mixes static content with dynamically-generated content. See JSP example here .
141. How are the JSP requests handled?
On the arrival of a JSP request, the browser first requests a page with a .jsp extension. Then, the Web server reads the request and using the JSP compiler, the Web server converts the JSP page into a servlet class. Notice that the JSP file is compiled only on the first request of the page, or if the JSP file has changed.The generated servlet class is invoked, in order to handle the browser's request. Once the execution of the request is over, the servlet sends a response back to the client. See how to get Request parameters in a JSP .
142. What are the advantages of JSP?
The advantages of using the JSP technology are shown below:
- JSP pages are dynamically compiled into servlets and thus, the developers can easily make updates to presentation code.
- JSP pages can be pre-compiled.
- JSP pages can be easily combined to static templates, including HTML or XML fragments, with code that generates dynamic content.
- Developers can offer customized JSP tag libraries that page authors access using an XML-like syntax.
- Developers can make logic changes at the component level, without editing the individual pages that use the application's logic.
143. What are Directives?
Directives are instructions that are processed by the JSP engine, when the page is compiled to a servlet. Directives are used to set page-level instructions, insert data from external files, and specify custom tag libraries.
144. What are the different types of Directives available in JSP?
Directives are defined between < %@ and % >.The different types of directives are shown below:
- Include directive: it is used to include a file and merges the content of the file with the current page.
- Page directive: it is used to define specific attributes in the JSP page, like error page and buffer.
- Taglib: it is used to declare a custom tag library which is used in the page.
145. What are JSP actions?
JSP actions use constructs in XML syntax to control the behavior of the servlet engine. They are executed when a JSP page is requested. They can be dynamically inserted into a file, re-use JavaBeans components, forward the user to another page, or generate HTML for the Java plugin.Some of the available actions are listed below:
- jsp:include includes a file, when the JSP page is requested.
- jsp:useBean finds or instantiates a JavaBean.
- jsp:setProperty sets the property of a JavaBean.
- jsp:getProperty gets the property of a JavaBean.
- jsp:forward forwards the requester to a new page.
- jsp:plugin generates browser-specific code.
146. What are Scriptlets?
In Java Server Pages (JSP) technology, a scriptlet is a piece of Java-code embedded in a JSP page. The scriptlet is everything inside the tags. Between these tags, a user can add any valid scriptlet.
147. What are Declarations?
Declarations are similar to variable declarations in Java. Declarations are used to declare variables for subsequent use in expressions or scriptlets. To add a declaration, you must use the sequences to enclose your declarations.
Sample code is added below to show the JSP declarations.
Declarations
<%! int j = 0; %> <%! int d, e, f; %> <%! Shape a = new Shape(); %>148. What are Expressions?
A JSP expression is used to insert the value of a scripting language expression, converted into a string, into the data stream returned to the client, by the web server. Expressions are defined between <% = and %> tags.
JSP Expresssion
<html> <head><title>My Blog</title></head> <body><p>Today's Date is: <%= (new java.util.Date()).toLocaleString()%></p></body> </html>149. What is meant by implicit objects and what are they?
JSP implicit objects are those Java objects that the JSP Container makes available to developers in each page. A developer can call them directly, without being explicitly declared. JSP Implicit Objects are also called pre-defined variables.The following objects are considered implicit in a JSP page:
- 應(yīng)用
- 頁
- request
- 響應(yīng)
- session
- 例外
- 出
- 配置
- pageContext
JSP sample tags for disabling session is shown below:
Disabling Session
<%@ page session=“false” %>150. What are the different tags provided in JSTL?
There are 5 type of JSTL tags:
Core:
- Variable support
- 流量控制
- URL management
- 雜
XML:
- 核心
- 流量控制
- 轉(zhuǎn)型
Internationalization:
- 語言環(huán)境
- Message formatting
- Number and date formatting
Database:
- 的SQL
功能:
- Collection length
- String manipulation
Want more Java interview questions?
你還在和我們在一起嗎? Wow, that was a huge article about different types Java Interview Questions. 如果您喜歡此功能,請訂閱我們的時事通訊,以享受每周更新和免費白皮書! 另外,請查看我們的課程以獲得更高級的培訓(xùn)!
So, what other Java Interview Questions are there? 在評論中讓我們知道,我們將在文章中添加它們! 編碼愉快!
Java Interview Questions was last updated on Aug. 07th, 2019
翻譯自: https://www.javacodegeeks.com/java-interview-questions.html
總結(jié)
以上是生活随笔為你收集整理的150个Java面试问答-最终清单(PDF下载)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: HashMap如何在Java中工作
- 下一篇: excel向左滑快捷键(excel表格左