Skip to main content

Posts

Important Java Question?

Which rules do you have to follow in order to implement an immutable class? • All fields should be final and private. • There should be not setter methods. • The class itself should be declared final in order to prevent subclasses to violate the principle of immutability. • If fields are not of a primitive type but a reference to another object: – There should not be a getter method that exposes the reference directly to the caller. – Don’t change the referenced objects (or at least changing these references is not visisble to clients of the object).
Recent posts

Compact Strings -  Java 9 Feature

Motivation The current implementation of the String class stores characters in a char array, using two bytes (sixteen bits) for each character. Data gathered from many different applications indicates that strings are a major component of heap usage and, moreover, that most String objects contain only Latin-1 characters. Such characters require only one byte of storage, hence half of the space in the internal char arrays of such String objects is going unused Description We propose to change the internal representation of the String class from a UTF-16 char array to a byte array plus an encoding-flag field. The new String class will store characters encoded either as ISO-8859-1/Latin-1 (one byte per character), or as UTF-16 (two bytes per character), based upon the contents of the string. The encoding flag will indicate which encoding is used. String-related classes such as AbstractStringBuilder, StringBuilder, and StringBuffer will be updated to use the same representation, as wi

56 to 60 Java Questions

56. What is the purpose of apache tomcat? Apache server is a standalone server that is used to test servlets and create JSP pages. It is free and open source that is integrated in the Apache web server. It is fast, reliable server to configure the applications but it is hard to install. It is a servlet container that includes tools to configure and manage the server to run the applications. It can also be configured by editing XML configuration files. 57. Where pragma is used? Pragma is used inside the servlets in the header with a certain value. The value is of no-cache that tells that a servlets is acting as a proxy and it has to forward request. Pragma directives allow the compiler to use machine and operating system features while keeping the overall functionality with the Java language. These are different for different compilers. 58. Briefly explain daemon thread. Daemon thread is a low priority thread which runs in the background performs garbage collection operation for th

51 to 55 Java Questions

51. What is the difference between a constructor and a method? A constructor is a member function of a class that is used to create objects of that class. It has the same name as the class itself, has no return type, and is invoked using the new operator. A method is an ordinary member function of a class. It has its own name, a return type (which may be void), and is invoked using the dot operator. 52. What will happen to the Exception object after exception handling? Exception object will be garbage collected. 53. Difference between static and dynamic class loading. Static class loading: The process of loading a class using new operator is called static class loading. Dynamic class loading: The process of loading a class at runtime is called dynamic class loading. Dynamic class loading can be done by using Class.forName(….).newInstance(). 54. Explain the Common use of EJB The EJBs can be used to incorporate business logic in a web-centric application. The EJBs can be used to

46 to 50 Java Questions

46. What is Constructor? A constructor is a special method whose task is to initialize the object of its class. It is special because its name is the same as the class name. They do not have return types, not even void and therefore they cannot return values. They cannot be inherited, though a derived class can call the base class constructor. Constructor is invoked whenever an object of its associated class is created. 47. What is an Iterator ? The Iterator interface is used to step through the elements of a Collection. Iterators let you process each element of a Collection. Iterators are a generic way to go through all the elements of a Collection no matter how it is organized. Iterator is an Interface implemented a different way for every Collection. 48. What is the List interface? The List interface provides support for ordered collections of objects. Lists may contain duplicate elements. 49. What is memory leak? A memory leak is where an unreferenced object that will ne

41 to 45 Java Questions

41. What is nested class? If all the methods of a inner class is static then it is a nested class. 42. What is HashMap and Map? Map is Interface and Hashmap is class that implements that. 43. What are different types of access modifiers? public: Any thing declared as public can be accessed from anywhere. private: Any thing declared as private can’t be seen outside of its class. protected: Any thing declared as protected can be accessed by classes in the same package and subclasses in the other packages. default modifier : Can be accessed only to classes in the same package. 44. What is the difference between Reader/Writer and InputStream/Output Stream? The Reader/Writer class is character-oriented and the InputStream/OutputStream class is byte-oriented. 45. What is servlet? Servlets are modules that extend request/response-oriented servers, such as java-enabled web servers. For example, a servlet might be responsible for taking data in an HTML order-entry form and applyi

36 to 40 Java questions

36. What is the difference between yielding and sleeping? When a task invokes its yield() method, it returns to the ready state. When a task invokes its sleep() method, it returns to the waiting state. 37. What is the difference between preemptive scheduling and time slicing? Under preemptive scheduling, the highest priority task executes until it enters the waiting or dead states or a higher priority task comes into existence. Under time slicing, a task executes for a predefined slice of time and then reenters the pool of ready tasks. The scheduler then determines which task should execute next, based on priority and other factors. 38. What is mutable object and immutable object? If a object value is changeable then we can call it as Mutable object. (Ex., StringBuffer, …) If you are not allowed to change the value of an object, it is immutable object. (Ex., String, Integer, Float, …) 39. What is the purpose of Void class? The Void class is an uninstantiable placeholder class to

31 to 35 java questions

31. What is a Java Bean? A Java Bean is a software component that has been designed to be reusable in a variety of different environments. 32. What are checked exceptions? Checked exception are those which the Java compilerforces you to catch. e.g. IOException are checked Exceptions. 33. What are runtime exceptions? Runtime exceptions are those exceptions that are thrown at runtime because of either wrong input data or because of wrong business logic etc. These are not checked by the compiler at compile time. 34. What is the difference between error and an exception? An error is an irrecoverable condition occurring at runtime. Such as OutOfMemory error. These JVM errors and you can not repair them at runtime. While exceptions are conditions that occur because of bad input etc. e.g. FileNotFoundException will be thrown if the specified file does not exist. Or a NullPointerException will take place if you try using a null reference. In most of the cases it is possible to recover f

26 to 30 Questions of Java

26. What is the difference between this() and super()? this() can be used to invoke a constructor of the same class whereas super() can be used to invoke a super class constructor. 27. What is Domain Naming Service(DNS)? It is very difficult to remember a set of numbers(IP address) to connect to the Internet. The Domain Naming Service(DNS) is used to overcome this problem. It maps one particular IP address to a string of characters. For example, www. mascom. com implies com is the domain name reserved for US commercial sites, moscom is the name of the company and www is the name of the specific computer, which is mascom’s server. 28. What is URL? URL stands for Uniform Resource Locator and it points to resource files on the Internet. URL has four components: http://www. address. com:80/index.html, where http – protocol name, address – IP address or host name, 80 – port number and index.html – file path. 29. What is RMI and steps involved in developing an RMI object? Remote Metho

16 to 20 Java questions

16. How do you set security in applets? using setSecurityManager() method 17. What is a layout manager and what are different types of layout managers available in java AWT? A layout manager is an object that is used to organize components in a container. The different layouts are available are FlowLayout, BorderLayout, CardLayout, GridLayout and GridBagLayout 18. What is JDBC? JDBC is a set of Java API for executing SQL statements. This API consists of a set of classes and interfaces to enable programs to write pure Java Database applications. 19. What are drivers available? a) JDBC-ODBC Bridge driver b) Native API Partly-Java driver c) JDBC-Net Pure Java driver d) Native-Protocol Pure Java driver 20. What is stored procedure? Stored procedure is a group of SQL statements that forms a logical unit and performs a particular task. Stored Procedures are used to encapsulate a set of operations or queries to execute on database. Stored procedures can be compiled and executed

Latest Java 6 to 10

6. What are the access modifiers in java ? There are 3 access modifiers. Public, protected and private, and the default one if no identifier is specified is called friendly, but programmer cannot specify the friendly identifier explicitly. 7. What is are packages? A package is a collection of related classes and interfaces providing access protection and namespace management. 8. What is meant by Inheritance and what are its advantages? Inheritance is the process of inheriting all the features from a class. The advantages of inheritance are reusability of code and accessibility of variables and methods of the super class by subclasses. 9. What is the difference between superclass and subclass? A super class is a class that is inherited whereas sub class is a class that does the inheriting. 10. What is an abstract class? An abstract class is a class designed with implementation gaps for subclasses to fill in and is deliberately incomplete.

Latest Java 11 to 15

11. What are the states associated in the thread? Thread contains ready, running, waiting and dead states. 12. What is synchronization? Synchronization is the mechanism that ensures that only one thread is accessed the resources at a time. 13. What is deadlock? When two threads are waiting each other and can’t precede the program is said to be deadlock. 14. What is an applet? Applet is a dynamic and interactive program that runs inside a web page displayed by a java capable browser 15. What is the lifecycle of an applet? init() method – Can be called when an applet is first loaded start() method – Can be called each time an applet is started. paint() method – Can be called when the applet is minimized or maximized. stop() method – Can be used when the browser moves off the applet’s page. destroy() method – Can be called when the browser is finished with the applet.

Daily Java questions

1​. What do you know about Java? Java is a high-level programming language originally developed by Sun Microsystems and released in 1995. Java runs on a variety of platforms, such as Windows, Mac OS, and the various versions of UNIX. 2. What are the supported platforms by JavaProgramming Language? Java runs on a variety of platforms, such as Windows, Mac OS, and the various versions of UNIX/Linux like HP-Unix, Sun Solaris, Redhat Linux, Ubuntu, CentOS, etc. 3. List any five features of Java? Some features include Object Oriented Platform Independent Robust Interpreted Multi-threaded 4. Why is Java Architectural Neutral? It’s compiler generates an architecture-neutral object file format, which makes the compiled code to be executable on many processors, with the presence of Java runtime system. 5. What is a singleton class? Give a practical example of its usage. A singleton class in java can have only one instance and hence all its methods and variables belong to just one i

File Dialog In AWT

File Dialog: import java.awt.*; import java.awt.event.*; public class DialogApplication extends Frame implements ActionListener, WindowListener { Button l,s; TextField tf; public static void main(String s[]) { DialogApplication da=new DialogApplication(); da.setVisible(true); da.setSize(200,200); } DialogApplication() { super("Dialog Application"); setLayout(new FlowLayout()); l=new Button("Load"); l.addActionListener(this); add(l); s=new Button("Save"); s.addActionListener(this); add(s); tf=new TextField(20); add(tf); addWindowListener(this); } public void actionPerformed(ActionEvent ae) { FileDialog fd; if (ae.getSource() == l) { fd=new FileDialog(this, "FileDialog",FileDialog.LOAD); } else { fd=new FileDialog(this, "FileDialog",FileDialog.SAVE); } fd.show(); String filename=fd.getFile(); if(filename!=null) { tf.setText(fi

Dialogs and File Dialogs

Dialogs and File Dialogs import java.awt.*; import java.awt.event.*; public class MessageDialogDemo extends Frame implements ActionListener { Button b; public static void main(String s[]) { MessageDialogDemo md=new MessageDialogDemo(); md.setVisible(true); md.setSize(300,300); } MessageDialogDemo() { super("Message Dialog Demo......."); setLayout(new FlowLayout()); b=new Button("Message Dialog"); b.addActionListener(this); add(b); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent we) { System.exit(0); } }); } public void actionPerformed(ActionEvent ae) { String msg="This is the message"; MessageDialog md= new MessageDialog(this, "Message Dialog", true, msg); md.show(); } } class MessageDialog extends Dialog implements ActionListener { Button ok; MessageDialog(Frame parent, String title, boolean mode, String msg) { supe

Menus & Menubars

Menus & Menubars import java.applet.*; import java.awt.*; import java.awt.event.*; /*<applet code="MenuBarDemo" width=300 height=300></applet>*/ class MenuFrame extends Frame implements ActionListener, ItemListener, WindowListener { MenuBarDemo mbd; MenuFrame(String title, MenuBarDemo mbd) { super(title); this.mbd=mbd; addWindowListener(this); MenuBar mb=new MenuBar(); setMenuBar(mb); Menu file=new Menu("File"); mb.add(file); MenuItem open=new MenuItem("Open"); file.add(open); MenuItem save=new MenuItem("Save"); file.add(save); Menu edit=new Menu("Edit"); mb.add(edit); MenuItem cut=new MenuItem("Cut"); edit.add(cut); MenuItem copy=new MenuItem("Copy"); edit.add(copy); MenuItem paste=new MenuItem("Paste"); edit.add(paste); Menu option =new Menu("Option"); mb.add(option); CheckboxMenuItem zoom=new CheckboxM

Windows & Frames In AWT

Windows & Frames import java.awt.*; import java.awt.event.*; class Frame1 extends Frame { Frame1(String title) { super(title); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent we) { System.exit(0); } }); } } public class FrameDemo { public static void main(String a[]) { Frame1 f1=new Frame1("This is title"); f1.show(); f1.setSize(200,300); } }

Panels in AWT

Panels: import java.applet.*; import java.awt.*; /*<applet code="PanelDemo" width=300 height=300></applet>*/ public class PanelDemo extends Applet { public void  init() { setLayout(new BorderLayout()); Panel pn=new Panel(); Button b1=new Button("Button 1"); pn.add(b1); Button b2=new Button("Button 2"); pn.add(b2); add(pn,"North"); Panel pe=new Panel(); Button b3=new Button("Button 3"); pe.add(b3); add(pe,"East"); Panel pw=new Panel(); Button b4=new Button("Button 4"); pw.add(b4); add(pw,"West"); Panel ps=new Panel(); Button b5=new Button("Button 5"); ps.add(b5); Button b6=new Button("Button 6"); ps.add(b6); add(ps,"South"); } }

Grid Layout & Insets

Grid Layout & Insets import java.applet.*; import java.awt.*; /*<applet code="GridLayoutDemo" width=300 height=300></applet>*/ public class GridLayoutDemo extends Applet { public void  init() { setLayout(new GridLayout(3,2)); Button b1=new Button("Button 1"); Button b2=new Button("Button 2"); Button b3=new Button("Button 3"); Button b4=new Button("Button 4"); Button b5=new Button("Button 5"); Button b6=new Button("Button 6"); add(b1); add(b2); add(b3); add(b4); add(b5); add(b6); } public Insets getInsets() { return new Insets(10,10,10,10); } }

Border Layout

Border Layout import java.applet.*; import java.awt.*; /*<applet code="BorderLayoutDemo" width=300 height=300></applet>*/ public class BorderLayoutDemo extends Applet { public void  init() { setLayout(new BorderLayout(5,5)); Button b1=new Button("North1"); Button b2=new Button("South1"); Button b3=new Button("East"); Button b4=new Button("West"); Button b5=new Button("Center"); add(b1,"North"); add(b2,"South"); add(b3,"East"); add(b4,"West"); add(b5,"Center"); } }

Flow layout

Flow Layout: import java.applet.*; import java.awt.*; /*<applet code="FlowLayoutDemo" width=300 height=300></applet>*/ public class FlowLayoutDemo extends Applet { public void  init() { setLayout(new FlowLayout(FlowLayout.LEFT,5,5)); for(int i=0;i<30;i++) add(new Button("Button "+i)); } }

Example of Scroll bars in AWT

Scroll Bars: import java.applet.*; import java.awt.*; import java.awt.event.*; /*<applet code="ScrollBarDemo" width=300 height=300></applet>*/ public class ScrollBarDemo extends Applet implements AdjustmentListener { TextArea ta; public void init() { Scrollbar sb=new Scrollbar(Scrollbar.HORIZONTAL,50,5,0,100); sb.addAdjustmentListener(this); add(sb); ta=new TextArea(10,20); add(ta); } public void adjustmentValueChanged(AdjustmentEvent ae) { Scrollbar sb=(Scrollbar)ae.getAdjustable(); ta.append("Adjustment Event:"+sb.getValue()+"\n"); } }

Example of List in AWT

Lists: import java.applet.*; import java.awt.*; import java.awt.event.*; /*<applet code="ListDemo" width=300 height=300></applet>*/ public class ListDemo extends Applet implements ActionListener, ItemListener { public void init() { List lst=new List(); lst.add("Red"); lst.add("Green"); lst.add("Blue"); lst.add("Yellow"); lst.add("LightGray"); lst.addActionListener(this); lst.addItemListener(this); add(lst); } public void actionPerformed(ActionEvent ae) { String s=ae.getActionCommand(); if(s.equals("Red")) setBackground(Color.red); else if(s.equals("Green")) setBackground(Color.green); else if(s.equals("Blue")) setBackground(Color.blue); else if(s.equals("Yellow")) setBackground(Color.yellow); else if(s.equals("LightGray")) setBackground(Color.lightGray); } public void itemStateCh

Example of TextField & TextArea AWT

TextField & TextArea: import java.applet.*; import java.awt.*; import java.awt.event.*; /*<applet code="TextFieldDemo" width=300 height=300></applet>*/ public class TextFieldDemo extends Applet implements ActionListener, TextListener { TextArea ta; TextField tf; public void init() { tf=new TextField(20); tf.addActionListener(this); tf.addTextListener(this); add(tf); ta=new TextArea(10,20); add(ta); } public void actionPerformed(ActionEvent ae) { ta.append("ActionEvent: "+ae.getActionCommand()+"\n"); tf.setText(""); } public void textValueChanged(TextEvent te) { ta.append("TextEvent: "+tf.getText()+"\n"); } }

Example of Choice in AWT

Choices: import java.applet.*; import java.awt.*; import java.awt.event.*; /*<applet code="ChoiceDemo" width=300 height=300></applet>*/ public class ChoiceDemo extends Applet implements ItemListener { Label l1; public void init() { Choice c1=new Choice(); c1.addItem("Red"); c1.addItem("Green"); c1.addItem("Blue"); c1.addItem("Yellow"); c1.addItem("Orange"); c1.addItem("Gray"); c1.addItem("Pink"); c1.addItemListener(this); add(c1); } public void itemStateChanged(ItemEvent ie) { Choice c=(Choice)ie.getItemSelectable(); String s=c.getSelectedItem(); if(s.equals("Red")) setBackground(Color.red); else if(s.equals("Green")) setBackground(Color.green); else if(s.equals("Blue")) setBackground(Color.blue); else if(s.equals("Yellow")) setBackground(Color.yellow); else if(s.equals(&q

Example of Checkbox group in AWT

Checkbox Group: import java.applet.*; import java.awt.*; import java.awt.event.*; /*<applet code="CheckGroup" width=300 height=300></applet>*/ public class CheckGroup extends Applet implements ItemListener { Label l1; public void init() { CheckboxGroup cbg=new CheckboxGroup(); Checkbox c1=new Checkbox("Male",cbg,true); c1.addItemListener(this); add(c1); Checkbox c2=new Checkbox("Female",cbg,false); c2.addItemListener(this); add(c2); l1=new Label("                  "); add(l1); } public void itemStateChanged(ItemEvent ie) { Checkbox cb=(Checkbox)ie.getItemSelectable(); l1.setText(cb.getLabel()); } }

Example of Check box in AWT

Checkboxes: import java.applet.*; import java.awt.*; import java.awt.event.*; /*<applet code="CheckBoxDemo" width=300 height=300></applet>*/ public class CheckBoxDemo extends Applet implements ItemListener { Label l1; public void init() { Checkbox c1=new Checkbox("B.C.A."); c1.addItemListener(this); add(c1); Checkbox c2=new Checkbox("B.B.A."); c2.addItemListener(this); add(c2); Checkbox c3=new Checkbox("B.Com."); c3.addItemListener(this); add(c3); l1=new Label("                           "); add(l1); } public void itemStateChanged(ItemEvent ie) { Checkbox cb=(Checkbox)ie.getItemSelectable(); l1.setText(cb.getLabel()); } }

Example of Canvas in AWT

Canvas import java.applet.*; import java.awt.*; /*<applet code="CanvasDemo" width=500 height=200></applet>*/ class Canvas1 extends Canvas { public void paint(Graphics g) { g.setColor(Color.lightGray); Dimension d=getSize(); g.drawRect(0,0,d.width-1,d.height-1); g.drawLine(0,d.height/2,d.width,d.height/2); g.drawLine(d.width/2,0,d.width/2,d.height-1); g.setColor(Color.blue); double dx=4*Math.PI/d.width; double x=-2*Math.PI; int h=d.height; for(int i=0;i<d.width-1;i++) { int y1=(int)((h-h*Math.sin(x))/2); int y2=(int)((h-h*Math.sin(x+dx))/2); g.drawLine(i,y1,i+1,y2); x+=dx; } } } public class CanvasDemo extends Applet { public void init() { Canvas1 c1=new Canvas1(); c1.setSize(401,501); add(c1); } }

Example of button in AWT

Button: import java.applet.*; import java.awt.*; import java.awt.event.*; /*<applet code="ButtonDemo" width=300 height=100></applet>*/ public class ButtonDemo extends Applet implements ActionListener { Label l1; public void init() { Button b1 =new Button("Yes"); b1.addActionListener(this); add(b1); Button b2=new Button("No"); b2.addActionListener(this); add(b2); Button b3=new Button("Cancel"); b3.addActionListener(this); add(b3); l1=new Label(" "); add(l1); } public void actionPerformed(ActionEvent ae) { String str=ae.getActionCommand(); if(str.equals("Yes")) { l1.setText(str); } else if(str.equals("No")) { l1.setText(str); } else { l1.setText(str); } } }

Example of Label in AWT

***Label:*** import java.applet.*; import java.awt.*; /*<applet code="LabelDemo" width=300 height=300></applet>*/ public class LabelDemo extends Applet { public void init() { Label l1=new Label("Name",Label.LEFT); add(l1); Label l2=new Label("Address",Label.RIGHT); add(l2); Label l3=new Label("City",Label.CENTER); add(l3); } }

What is exception handling ?

An exception is an object that is generated at run-time to describe a problem encountered during the execution of a program.Some causes of exceptions are division by zero, array index out of bound, interrupted I/O, end of file, etc. Java allows to handle exceptions that occur during the execution of a program. ****Syntax**** try{try block}catch(ExceptionType arg1){catch code}catch(ExceptionType arg2){catch code}finally{finally block} ****Try block**** The try statement contains a block of statements closed by braces. This code will be monitored for exceptions. If any exceptions occur, it will be thrown using the throw statement.Immediately after the try block there is a sequence of catch blocks. Each catch block begins with catch statement. The argument is the exception object that contains When a problem occurs during execution of the try block, the JVM immediately stops executing the try block and looks for a catch block that can process that type of exception. ****W

What is Applet ?

***What is an Applet? An Applet is a program that can be referenced by an HTML source code of a web page. It is dynamically downloaded from a web server to a browser and it is executed in the environment provided by the browser. Applet Viewer can also be used to execute  the applet. ***FirstApplet.java import java.applet.Applet; import java.awt.Graphics; /*<applet code=“FirstApplet” width=200 height=200> </applet>*/ public class FirstApplet extends Applet { public void paint(Graphics g) { g.drawString(“Hello World”,20,100); } } *** In the above example, The first two line is importing the java.applet and java.awt.Graphics package. The third line is the comment entry which is used only for applet viewer to execute the applet using the HTML source code. The next line declares the FirstApplet class which extends Applet class. Note that each applet created by user must extend the Applet class. There is a paint() method defined whi

What is Servet ?

A servlet is a java class that extends an application hosted on a web server. Handles the HTTP request-response process (for our purposes) Often thought of as an applet that runs on a server. Provides a component base architecture for web development, using the Java Platform The foundation for Java Server Pages (JSP). Alternative to CGI scripting and platform specific server side applications.

How to Install WordPress

The five steps to install WordPress… Download the latest version of WordPress from WordPress.org. Upload those files to your web server, using FTP. Create a MySQL database and user for WordPress. Configure WordPress to connect to the newly-created database. Complete the installation and setup your new website!

How to Change Gmail Password

1.     Open the Gmail website in your browser. ...  2.    Sign in with the account you want to change the password for. ...  3.    Click the Gear button. ...  4.    Click Settings.  5.   Click the Accounts and Import tab.  6.   Click Change password.  7.    Enter your current password. ...  8.   Type a new password.