In java ,the exception handling mechanism handles abnormal and unexpected situations in a structured manner. As i told in previous tutorial when an exception is raised JRE searches for an exception handler (try-catch) in the method that caused exception.If handler not found there then it searches in calling method. The search goes on until The runtime system finds an appropriate exception handler ,that is situation where the type of exception caught by the handler is the same as the type of exception thown.
Detailed Example:-
//Except.java
public class Except{ public static void main(String a[]){ int result=0,num1=10,num2=0; try { result=num1/num2; }catch(Exception e) { System.out.println("Error divide by zero"); } System.out.println("Result is:"+result); } }
Explanation:- In above mentioned code the main method contains both try and catch. Since exception is raised in main thus first the runtime system will check main for exception handler,if it is there in this case present in same method main then it is fine displays message.
Multiple catch blocks:-
A single try block may have many catch blocks.This is necessary when the try block has statements that may result in different types of exceptions.Following code show Three type of exceptions to be trapped.
//Multiplecatch.java
public class Multiplecatch{ public static void main(String a[]) { int number[]={0,0}; int num1,num2,result=0; num1=10; num2=0; try { result=num1/num2; System.out.println(num1/number[2]); } catch(ArithmeticException e){ System.out.println("Error divide by zero"); } catch(ArrayIndexOutOfBoundsException e){ System.out.println("Error out of bounds"); } catch(Exception e){} System.out.println("result is:"+result); } }
Output:-Error divide by zero result is:0
Explanation:-
In code above try has two statements that may result in many exceptions. Here 3 catch blocks are following try block.
NOTE:- 1.The catch block that has the most specific exception class must be written first. 2.The subclass comes first than superclass that is ArithmeticException comes first than Exception class. because Exception is capable of handling all exceptions raised thus resulting in compiler error. 3.This will result in an compiler error stating Unreachable code. 4.Whenever an exception is raised on a particular statement ,the next statement will never get executed due to program flow interruption.
Nested try-catch:- In nested try-catch block we have one try-catch block inside another.Similarly a catch block can contain try-catch block.If lower level try-catch block does not have matching catch handler ,the outer try block is checked for it.
Exception handling works by transferring the execution of a program to an appropriate exception handler when an exception occurs. When an unexpected error occurs in a method ,java creates an object of type Exception . After creating the Exception object ,Java sends it to the program,by an action called throwing an exception.The exception object contains information about the type of error and the state of program when the exception occured.
You need to handle the exception using an exception handler and process application Therefore,we need a way to tell the JVM what code to execute when a certain exception happens. To do this, we use the try and catch keywords. The try is used to define a block of code in which exceptions may occur. This block of code is called a guarded region (which really means "risky code goes here"). One or more catch clauses match a specific exception (or group of exceptions—more on that later) to a block of code that handles it.
Sample code where exception is raised:-
/*public void compute(int num1,int num2){ int result; reult=num2/num1; }*/
When we pass two value as 10,0 Aritmetic exception is thrown as
"Exception in thread "main" java.lang.Aritmetic Exception: / zero at execpt.main(except.java:9)"
An Exception object is created to cause the program to stop and handle the exception.It expects an exception handler to handle the exception raised. whenever program is not guarded the default exception handler is invoked.
Basic Try and Catch syntax:-
try{ //serious statements that may cause exception } catch(....){ //Exception handler code goes here }
try:-The try block contains the serious stuff.I the try block governs the statements in which the chances of getting into exception is more.There is also a point to note that try need atleast a catch.Both are dependent on each other no one can be used without the other.
NOTE:-the very important point is that a try must be followed by a catch or series of catches immediately with no other instructions or expression in between.
REMEMBER:-The compiler does not allow any statement between a try block and its associated catch block.
catch:-The catch statement contains exception handling routines.The catch statement takes the object of the exception class that refers to the exception caught,as a parameter.Once the Exception is caught the code within catch will execute.
NOTE:-The scope of catch block is limited to try block only.
Example:-
only Snippet is provided for demo purpose
public void testexcept(int num1,int num2){ int result; try { result=num2/num1; }catch(ArithmeticException ae){ System.out.println("Exception Divide by zero"); } System.out.println(result); }
Basic Definition:- The term exception denotes an exceptional event that occured during program execution and which alters normal flow of instructions.Exception handling goes handy in situations where there is a possibility of unexpected or exceptional event.
Some unexpected situations are:- 1.Problem with network connectivity 2.arrays out of bounds 3.mathematical exceptions 4.Problem in I/O
Need for exception Handling:-
You cannot afford to have an application that stop working if requested file is missing. To handle situations like above to avoid a crash exception handling is done. Exception handling allows developers and programmers to detect errors easily without writing special code. Even better, it lets us keep exception-handling code cleanly separated from the exception-generating code. It also lets us use the same exception-handling code to deal with a range of possible exceptions.
The Exception class:-
The class which is on top of hierarchy is called Throwable.Two classes are derived from it. Error and Exception.
The Exception class is used for Exceptional conditions that have to be trapped in a program.
The Error class defines the conditions that usually do not occur in normal situations. That is Error class is mainly used for catastophic failures such as VirtualMachineError etc.
Mechanism:-
Whenever an exception is raised,The Java Runtime System searches for an exception handler in current method.If it does not found there then searches in calling method. If handler is present nowhere it takes system default action as printing stack trace.
Java Swing is a fully-featured user interface development kit for Java applications. Swings has been developed on the grounds of AWT(abstract windoe toolkit).It provides Rich Look and Feel for the graphical applications.It has cross platform functtionality since it is feature of Java.Swings include Buttons,Labels,TextBoxes,Trees,Scroll Bars etc.
Java Swing, 2nd edition includes :
A new chapter on Drag and Drop
Accessibility features for creating a user interface meeting the needs of all users
Coverage of the improved key binding infrastructure introduced in SDK 1.3
A new chapter on JFormattedTextField and input validation
Mac OS X coverage and examples
Coverage of the improved focus system introduced in SDK 1.4
Pluggable Look-and-Feel coverage
Coverage of the new layout manager, SpringLayout, from SDK 1.4
Properties tables that summarize important features of each component
Coverage of the 1.4 Spinner component
Details about using HTML in components
A new appendix listing bound actions for each component
A supporting web site with utilities, examples, and supplemental materials
It is an indespensible guide to all either experienced or a beginner programmer.Go for it and check it out.Free Download Here
Is “abc” a primitive value? - The String literal “abc” is not a primitive value. It is a String object. "
What restrictions are placed on the values of each case of a switch statement? - During compilation, the values of each case of a switch statement must evaluate to a value that can be promoted to an int value.
What modifiers may be used with an interface declaration? - An interface may be declared as public or abstract.
Is a class a subclass of itself? - A class is a subclass of itself.
What is the difference between a while statement and a do statement? - A while statement checks at the beginning of a loop to see whether the next loop iteration should occur. A do statement checks at the end of a loop to see whether the next iteration of a loop should occur. The do statement will always execute the body of a loop at least once.
What modifiers can be used with a local inner class? - A local inner class may be final or abstract.
What is the purpose of the File class? - The File class is used to create objects that provide access to the files and directories of a local file system.
Can an exception be rethrown? - Yes, an exception can be rethrown.
When does the compiler supply a default constructor for a class? - The compiler supplies a default constructor for a class if no other constructors are provided.
If a method is declared as protected, where may the method be accessed? - A protected method may only be accessed by classes or interfaces of the same package or by subclasses of the class in which it is declared.
Which non-Unicode letter characters may be used as the first character of an identifier? - The non-Unicode letter characters $ and _ may appear as the first character of an identifier
What restrictions are placed on method overloading? - Two methods may not have the same name and argument list but different return types.
What is casting? - There are two types of casting, casting between primitive numeric types and casting between object references. Casting between numeric types is used to convert larger values, such as double values, to smaller values, such as byte values. Casting between object references is used to refer to an object by a compatible class, interface, or array type reference.
What is the return type of a program’s main() method? - A program’s main() method has a void return type.
What class of exceptions are generated by the Java run-time system? - The Java runtime system generates RuntimeException and Error exceptions.
What class allows you to read objects directly from a stream? - The ObjectInputStream class supports the reading of objects from input streams.
What is the difference between a field variable and a local variable? - A field variable is a variable that is declared as a member of a class. A local variable is a variable that is declared local to a method.
How are this() and super() used with constructors? - this() is used to invoke a constructor of the same class. super() is used to invoke a superclass constructor.
What is the relationship between a method’s throws clause and the exceptions that can be thrown during the method’s execution? - A method’s throws clause must declare any checked exceptions that are not caught within the body of the method.
Why are the methods of the Math class static? - So they can be invoked as if they are a mathematical code library.
What are the legal operands of the instanceof operator? - The left operand is an object reference or null value and the right operand is a class, interface, or array type.
What an I/O filter? - An I/O filter is an object that reads from one stream and writes to another, usually altering the data in some way as it is passed from one stream to another.
If an object is garbage collected, can it become reachable again? - Once an object is garbage collected, it ceases to exist. It can no longer become reachable again.
What are E and PI? - E is the base of the natural logarithm and PI is mathematical value pi.
Are true and false keywords? - The values true and false are not keywords.
What is the difference between the File and RandomAccessFile classes? - The File class encapsulates the files and directories of the local file system. The RandomAccessFile class provides the methods needed to directly access data contained in any part of a file.
What happens when you add a double value to a String? - The result is a String object.
What is your platform’s default character encoding? - If you are running Java on English Windows platforms, it is probably Cp1252. If you are running Java on English Solaris platforms, it is most likely 8859_1.
Which package is always imported by default? - The java.lang package is always imported by default.
What interface must an object implement before it can be written to a stream as an object? - An object must implement the Serializable or Externalizable interface before it can be written to a stream as an object.
How can my application get to know when a HttpSession is removed? - Define a Class HttpSessionNotifier which implements HttpSessionBindingListener and implement the functionality what you need in valueUnbound() method. Create an instance of that class and put that instance in HttpSession.
Whats the difference between notify() and notifyAll()? - notify() is used to unblock one waiting thread; notifyAll() is used to unblock all of them. Using notify() is preferable (for efficiency) when only one blocked thread can benefit from the change (for example, when freeing a buffer back into a pool). notifyAll() is necessary (for correctness) if multiple threads should resume (for example, when releasing a “writer” lock on a file might permit all “readers” to resume).
Why can’t I say just abs() or sin() instead of Math.abs() and Math.sin()? - The import statement does not bring methods into your local name space. It lets you abbreviate class names, but not get rid of them altogether. That’s just the way it works, you’ll get used to it. It’s really a lot safer this way. However, there is actually a little trick you can use in some cases that gets you what you want. If your top-level class doesn’t need to inherit from anything else, make it inherit from java.lang.Math. That *does* bring all the methods into your local name space. But you can’t use this trick in an applet, because you have to inherit from java.awt.Applet. And actually, you can’t use it on java.lang.Math at all, because Math is a “final” class which means it can’t be extended.
Why are there no global variables in Java? - Global variables are considered bad form for a variety of reasons: Adding state variables breaks referential transparency (you no longer can understand a statement or expression on its own: you need to understand it in the context of the settings of the global variables), State variables lessen the cohesion of a program: you need to know more to understand how something works. A major point of Object-Oriented programming is to break up global state into more easily understood collections of local state, When you add one variable, you limit the use of your program to one instance. What you thought was global, someone else might think of as local: they may want to run two copies of your program at once. For these reasons, Java decided to ban global variables.
What does it mean that a class or member is final? - A final class can no longer be subclassed. Mostly this is done for security reasons with basic classes like String and Integer. It also allows the compiler to make some optimizations, and makes thread safety a little easier to achieve. Methods may be declared final as well. This means they may not be overridden in a subclass. Fields can be declared final, too. However, this has a completely different meaning. A final field cannot be changed after it’s initialized, and it must include an initializer statement where it’s declared. For example, public final double c = 2.998; It’s also possible to make a static field final to get the effect of C++’s const statement or some uses of C’s #define, e.g. public static final double c = 2.998;
What does it mean that a method or class is abstract? - An abstract class cannot be instantiated. Only its subclasses can be instantiated. You indicate that a class is abstract with the abstract keyword like this:
public abstract class Container extends Component {
Abstract classes may contain abstract methods. A method declared abstract is not actually implemented in the current class. It exists only to be overridden in subclasses. It has no body. For example,
public abstract float price();
Abstract methods may only be included in abstract classes. However, an abstract class is not required to have any abstract methods, though most of them do. Each subclass of an abstract class must override the abstract methods of its superclasses or itself be declared abstract.
What is a transient variable? - transient variable is a variable that may not be serialized.
How are Observer and Observable used? - Objects that subclass the Observable class maintain a list of observers. When an Observable object is updated it invokes the update() method of each of its observers to notify the observers that it has changed state. The Observer interface is implemented by objects that observe Observable objects.
Can a lock be acquired on a class? - Yes, a lock can be acquired on a class. This lock is acquired on the class’s Class object.
What state does a thread enter when it terminates its processing? - When a thread terminates its processing, it enters the dead state.
How does Java handle integer overflows and underflows? - It uses those low order bytes of the result that can fit into the size of the type allowed by the operation.
What is the difference between the >> and >>> operators? - The >> operator carries the sign bit when shifting right. The >>> zero-fills bits that have been shifted out.
Is sizeof a keyword? - The sizeof operator is not a keyword.
Does garbage collection guarantee that a program will not run out of memory? - Garbage collection does not guarantee that a program will not run out of memory. It is possible for programs to use up memory resources faster than they are garbage collected. It is also possible for programs to create objects that are not subject to garbage collection
Can an object’s finalize() method be invoked while it is reachable? - An object’s finalize() method cannot be invoked by the garbage collector while the object is still reachable. However, an object’s finalize() method may be invoked by other objects.
What value does readLine() return when it has reached the end of a file? - The readLine() method returns null when it has reached the end of a file.
Can a for statement loop indefinitely? - Yes, a for statement can loop indefinitely. For example, consider the following: for(;;) ;
To what value is a variable of the String type automatically initialized? - The default value of an String type is null.
What is a task’s priority and how is it used in scheduling? - A task’s priority is an integer value that identifies the relative order in which it should be executed with respect to other tasks. The scheduler attempts to schedule higher priority tasks before lower priority tasks.
What is the range of the short type? - The range of the short type is -(2^15) to 2^15 - 1.
What is the purpose of garbage collection? - The purpose of garbage collection is to identify and discard objects that are no longer needed by a program so that their resources may be reclaimed and reused.
What do you understand by private, protected and public? - These are accessibility modifiers. Private is the most restrictive, while public is the least restrictive. There is no real difference between protected and the default type (also known as package protected) within the context of the same package, however the protected keyword allows visibility to a derived class in a different package.
What is Downcasting ? - Downcasting is the casting from a general to a more specific type, i.e. casting down the hierarchy
Can a method be overloaded based on different return type but same argument type ? - No, because the methods can be called without using their return type in which case there is ambiquity for the compiler
What happens to a static var that is defined within a method of a class ? - Can’t do it. You’ll get a compilation error
How many static init can you have ? - As many as you want, but the static initializers and class variable initializers are executed in textual order and may not refer to class variables declared in the class whose declarations appear textually after the use, even though these class variables are in scope.
What is the difference amongst JVM Spec, JVM Implementation, JVM Runtime ? - The JVM spec is the blueprint for the JVM generated and owned by Sun. The JVM implementation is the actual implementation of the spec by a vendor and the JVM runtime is the actual running instance of a JVM implementation
Describe what happens when an object is created in Java? - Several things happen in a particular order to ensure the object is constructed properly: Memory is allocated from heap to hold all instance variables and implementation-specific data of the object and its superclasses. Implemenation-specific data includes pointers to class and method data. The instance variables of the objects are initialized to their default values. The constructor for the most derived class is invoked. The first thing a constructor does is call the consctructor for its superclasses. This process continues until the constrcutor for java.lang.Object is called, as java.lang.Object is the base class for all objects in java. Before the body of the constructor is executed, all instance variable initializers and initialization blocks are executed. Then the body of the constructor is executed. Thus, the constructor for the base class completes first and constructor for the most derived class completes last.
What does the “final” keyword mean in front of a variable? A method? A class? - FINAL for a variable: value is constant. FINAL for a method: cannot be overridden. FINAL for a class: cannot be derived
What is the difference between instanceof and isInstance? - instanceof is used to check to see if an object can be cast into a specified type without throwing a cast class exception. isInstance() Determines if the specified Object is assignment-compatible with the object represented by this Class. This method is the dynamic equivalent of the Java language instanceof operator. The method returns true if the specified Object argument is non-null and can be cast to the reference type represented by this Class object without raising a ClassCastException. It returns false otherwise.
Why does it take so much time to access an Applet having Swing Components the first time? - Because behind every swing component are many Java objects and resources. This takes time to create them in memory. JDK 1.3 from Sun has some improvements which may lead to faster execution of Swing applications.
Class A template that describes the kinds of state and behavior that objects of its type support.
Object At runtime, when the Java Virtual Machine (JVM) encounters the new keyword, it will use the appropriate class to make an object which is an instance of that class. That object will have its own state, and access to all of the behaviors defined by its class.Also some memory is allocated on the heap.
State (instance variables) Each object (instance of a class) will have its own unique set of instance variables as defined in the class. Collectively, the values assigned to an object's instance variables make up the object's state.
Behavior (methods) When a programmer creates a class, He creates methods for that class. Methods are where the class' logic is stored. Methods are where the real work gets done. They are where algorithms get executed, and data gets manipulated.
Inheritance Central to Java and other object-oriented languages is the concept of inheritance, which allows code defined in one class to be reused in other classes. In Java, you can define a general (abstract) superclass, and then extend it with more specific subclasses. The superclass knows nothing of the classes that inherit from it, but all of the subclasses that inherit from the superclass must explicitly declare the inheritance relationship. A subclass that inherits from a superclass is automatically given accessible instance variables and methods defined by the superclass, but is also free to override superclass methods to define more specific behavior.This is very useful feature of Java as it provides specific functionality to every subclass irrespective of Superclass.
Interfaces Interfaces are like a 100-percent abstract superclass that defines the methods a subclass must support. In other words, a Bus interface might declare that all Animal implementation classes have an run() method, but the Bus interface doesn't supply any logic for the run() method. That means it's up to the classes that implement the Car interface to define the actual code for how that particular Bus type behaves when its run() method is invoked.
Legal Identifiers
Rules:-
1. Identifiers must start with a letter, a currency character ($), or a connecting character such as the underscore ( _ ). Identifiers cannot start with a number! 2. After the first character, identifiers can contain any combination of letters, currency characters, connecting characters, or numbers. 3. In practice, there is no limit to the number of characters an identifier can contain. 4. You can't use a Java keyword as an identifier. Table 1-1 lists all of the Java keywords including one new one for 5.0, enum. 5. Identifiers in Java are case-sensitive; foo and FOO are two different identifiers.
Examples of legal and illegal identifiers follow, first some legal identifiers: int _name; int $a; int ___2_w; int _$; int this_is_a_name_for_an_identifier;
The following are illegal (it's your job to recognize why): int :a; int -bb; int a#; int .d; int 9g;
Complete List of Java Keywords (assert added in 1.4, enum added in 1.5)
Namaing Conventions:- 1.Classes and interfaces The first letter should be capitalized, and if several words are linked together to form the name, the first letter of the inner words should be uppercase
For example: Cat Account Printer
For interfaces, the names should typically be adjectives like
ActionListener Beauty
2.Methods The first letter should be lowercase, and then normal camelCase rules should be used. For example: getDate doSomeWork setCustomerid
3.Variables Like methods, the camelCase format should be used, starting with a lowercase letter. Some examples: labelWidth accountNumber myYahoo
4.Constants Java constants are created by marking variables static and final. They should be named using uppercase letters with underscore characters as separators: MIN_HEIGHT
From today onwards I am launching an extensive interview question series which not only include Java but all other stuff ,which is expected from a Computer Engineer and Software Engineer.
JAVA Interview Questions
1.What is garbage collection? What is the process that is responsible for doing that in java? - Reclaiming the unused memory by the invalid objects. Garbage collector is responsible for this process
2.What kind of thread is the Garbage collector thread? - It is a daemon thread.
3.What is a daemon thread? - These are the threads which can run without user intervention. The JVM can exit when there are daemon thread by killing them abruptly.
4.How will you invoke any external process in Java? - Runtime.getRuntime().exec(….)
5.What is the finalize method do? - Before the invalid objects get garbage collected, the JVM give the user a chance to clean up some resources before it got garbage collected.
6.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, …)
7.What is the basic difference between string and stringbuffer object? - String is an immutable object. StringBuffer is a mutable object.
8.What is the purpose of Void class? - The Void class is an uninstantiable placeholder class to hold a reference to the Class object representing the primitive Java type void.
9.What is reflection? - Reflection allows programmatic access to information about the fields, methods and constructors of loaded classes, and the use reflected fields, methods, and constructors to operate on their underlying counterparts on objects, within security restrictions.
10.What is the base class for Error and Exception? - Throwable
11.What is the byte range? -128 to 127
12.What is the implementation of destroy method in java.. is it native or java code? - This method is not implemented.
13.What is a package? - To group set of classes into a single unit is known as packaging. Packages provides wide namespace ability.
14.What are the approaches that you will follow for making a program very efficient? - By avoiding too much of static methods avoiding the excessive and unnecessary use of synchronized methods Selection of related classes based on the application (meaning synchronized classes for multiuser and non-synchronized classes for single user) Usage of appropriate design patterns Using cache methodologies for remote invocations Avoiding creation of variables within a loop and lot more.
15.What is a DatabaseMetaData? - Comprehensive information about the database as a whole.
16.What is Locale? - A Locale object represents a specific geographical, political, or cultural region
17.How will you load a specific locale? - Using ResourceBundle.getBundle(…);
18.What is JIT and its use? - Really, just a very fast compiler… In this incarnation, pretty much a one-pass compiler – no offline computations. So you can’t look at the whole method, rank the expressions according to which ones are re-used the most, and then generate code. In theory terms, it’s an on-line problem.
19.Is JVM a compiler or an interpreter? - Interpreter
20.When you think about optimization, what is the best way to findout the time/memory consuming process? - Using profiler
21.What is the purpose of assert keyword used in JDK1.4.x? - In order to validate certain expressions. It effectively replaces the if block and automatically throws the AssertionError on failure. This keyword should be used for the critical arguments. Meaning, without that the method does nothing.
22.How will you get the platform dependent values like line separator, path separator, etc., ? - Using Sytem.getProperty(…) (line.separator, path.separator, …)
23.What is skeleton and stub? what is the purpose of those? - Stub is a client side representation of the server, which takes care of communicating with the remote server. Skeleton is the server side representation. But that is no more in use… it is deprecated long before in JDK.
24.What is the final keyword denotes? - final keyword denotes that it is the final implementation for that method or variable or class. You can’t override that method/variable/class any more.
25.What is the significance of ListIterator? - You can iterate back and forth.
26.What is the major difference between LinkedList and ArrayList? - LinkedList are meant for sequential accessing. ArrayList are meant for random accessing.
27.What is nested class? - If all the methods of a inner class is static then it is a nested class.
28.What is inner class? - If the methods of the inner class can only be accessed via the instance of the inner class, then it is called inner class.
29.What is composition? - Holding the reference of the other class within some other class is known as composition.
30.What is aggregation? - It is a special type of composition. If you expose all the methods of a composite class and route the method call to the composite method through its reference, then it is called aggregation.
31.What are the methods in Object? - clone, equals, wait, finalize, getClass, hashCode, notify, notifyAll, toString
32.Can you instantiate the Math class? - You can’t instantiate the math class. All the methods in this class are static. And the constructor is not public.
33.What is singleton? - It is one of the design pattern. This falls in the creational pattern of the design pattern. There will be only one instance for that entire JVM. You can achieve this by having the private constructor in the class. For eg., public class Singleton { private static final Singleton s = new Singleton(); private Singleton() { } public static Singleton getInstance() { return s; } // all non static methods … }
34.What is DriverManager? - The basic service to manage set of JDBC drivers.
35.What is Class.forName() does and how it is useful? - It loads the class into the ClassLoader. It returns the Class. Using that you can get the instance ( “class-instance".newInstance() ).
JLabels in Swing can contain text, images or both. JLabel do not generate an action event though it works on Mouse Events.Like MouseMotion,MouseListener etc. We can also add non-functional labels in our interface(GUI). You can also specify the position of the text relative to the image. Also we can align,specify border,size and many more properties. Constructors:-JLabel class has following Constructors
JLabel() // Creates aJLabel without an image and with empty string title JLabel(Icon icon) //Creates a JLabel instance with specified image as title JLabel(Icon image,int horizontalAlignment)// Creates a JLabel object with image and alignment JLabel(String text)//JLabel with some text as title JLabel(String text,Icon image,int horizontalAlignment) JLabel(String text ,int horizontalalignment) Example:- The following exmaple is for simple label showing only text:-
import javax.swing.*;
public class SimpleJLabel extends JFrame{
public static void main(String[] args) {
JLabel label = new JLabel("A Simple Text Label");
JFrame frame = new JFrame();
frame.getContentPane().add(label);
frame.pack();
frame.setVisible(true); } } Example:- The Following Example shows setting up an Icon on Label
import javax.swing.*;
public class SimpleJLabel extends JFrame{
public static void main(String[] args) {
JLabel label = new JLabel(); label.setIcon(new ImageIcon("e1.png"));
JFrame frame = new JFrame();
frame.getContentPane().add(label);
frame.pack();
frame.setVisible(true);
}
}
You can also set many more properties like mnemonics,tooltiptext alignment etc.Read more...
Jbutton is the standrad command button used in Java.It is mainly used for event driven programming.A JButton when clicked fires an event which is handled by an event handler which in response do some work as indicated in hadler.On click the JButton takes some set of input and process that.The JButton is a Swing Component.
JButton Class has following constructors:-
JButton() // Creates a button with no text or icon
JButton(Action a) //Creates a button where are properties are tak
en from action supplied
JButton(Icon icon)//Creates a button with a icon
JButton(String text)//Creates a button with some text
JButton(String text ,Icon icon)//Creates button with both text and icon
Features of JButton:-
1.JButton applies event handling.
2.JButton has a different look and feel for enabled and disabled buttons.
3.You can set mnemonics for JButtons.
4.TooltipText can also be set for JButtons.
Following example shows the application of all above mentioned features:- In this example there are buttons which on click disable and enable the corresponding buttons. The program follows:-
Java covers six relational operators (<, <=, >, >=, ==, and !=). Relational operators always result in a boolean value. This boolean value is most often used in an if test, as follows, int x = 6; if (x < b =" 10"> 99; System.out.println("The value of b is " + b); } }
Java has four relational operators that can be used to compare any combination of integers, floating-point numbers, or characters: 1. > greater than 2. >= greater than or equal to 3. < style="color: rgb(0, 0, 153);">"Equality" Operators Java also has two equality operators that compare two similar "things" and return a boolean the represents what's true about the two "things" being equal. These operators are 1.== equals (also known as "equal to") 2.!= not equals (also known as "not equal to")
Each individual comparison can involve two numbers (including char), two boolean values, or two object reference variables. You can't compare incompatible types, however. What would it mean to ask if a boolean is equal to a char? Or if a Button is equal to a String array?There are four different types of things that can be tested:
This program produces the following output: character 'a' == 'a'? true character 'a' == 'b'? false 5 != 6? true 5.0 == 5L? true true == false? false
Don't mistake = for == in a boolean expression. The following code is legal: boolean b = false; if (b = true) { System.out.println("b is true"); } else { System.out.println("b is false"); }
You might be tempted to think the output is b is false but look at the boolean test in line 2. The boolean variable b is not being compared to true, it's set to true, so the println executes and we get b is true .
Equality for Reference Variables
Two reference variables can refer to the same object, as the following code demonstrates: JButton a = new JButton("Enter"); JButton b = a;
After running this code, both variable a and variable b will refer to the same object .Reference variables can be tested to see if they refer to the same object by using the == operator. Remember, the == operator is looking at the bits in the variable, so for reference variables this means that if the bits in both reference variables are identical, then both refer to the same object.
Look at the following code: import javax.swing.JButton; class CompareRef { public static void main(String[] args) { JButton a = new JButton("Enter"); JButton b = new JButton("Exit"); JButton c = a; System.out.println("Is reference a == b? " + (a == b)); System.out.println("Is reference a == c? " + (a == c)); } }
This code creates three reference variables. The first two, a and b, are separate JButton objects that happen to have the same label. The third reference variable, c, is initialized to refer to the same object that a refers to. When this program runs, the following output is produced: Is reference a == b? false Is reference a == c? true This shows us that a and c reference the same instance of a JButton.
Equality for Enums
Once you've declared an enum, it's not expandable.Of course, you can have as many variables as you'd like refer to a given enum constant, so it is important to be able to compare two enum reference variables to see if they're "equal,". You can use either the == operator or the equals() method to determine if two variables are referring to the same enum constant: class Enum{ enum Color {RED, BLUE} ; public static void main(String[] args) { Color c1 = Color.RED; Color c2 = Color.RED; if(c1 == c2) { System.out.println("=="); } if(c1.equals(c2)) { System.out.println("dot equals"); } } }
output:- == dot equals
instanceof Comparison The instanceof operator is used for object reference variables only, and you can use it to check whether an object is of a particular type. By type, we mean class or interface type.The following simple example
public static void main(String[] args) { String s = new String("fun"); if (s instanceof String) { System.out.print("s is a String"); } }
prints this: s is a String
Even if the object being tested is not an actual instantiation of the class type on the right side of the operator, instanceof will still return true if the object being compared is assignment compatible with the type on the right. The following example demonstrates a common use for instanceof: testing an object to see if it's an instance of one of its subtypes, before attempting a "downcast":
class A { } class B extends A { public static void main (String [] args) { A myA = new B(); m2(myA); } public static void m2(A a) { if (a instanceof B) ((B)a).doBstuff(); // downcasting an A reference // to a B reference } public static void doBstuff() { System.out.println("'a' refers to a B"); } } instanceof Comparison
The preceding code compiles and produces the output: 'a' refers to a B
You can test an object reference against its own class type, or any of its superclasses. This means that any object reference will evaluate to true if you use the instanceof operator against type Object, as follows, B b = new B(); if (b instanceof Object) { System.out.print("b is definitely an Object"); } which prints this: b is definitely an Object
Look for instanceof questions that test whether an object is an instance of an interface, when the object's class implements the interface indirectly. An indirect implementation occurs when one of an object's superclasses implements an interface, but the actual class of the instance does not—for example
interface Foo { } class A implements Foo { } class B extends A { } ... A a = new A(); B b = new B(); the following are true: a instanceof Foo b instanceof A b instanceof Foo // implemented indirectly
Remember:-An object is said to be of a particular interface type (meaning it will pass the instanceof test) if any of the object's superclasses implement the interface
In addition, it is legal to test whether the null reference is an instance of a class. This will always result in false, of course. For example:
class Instance { public static void main(String [] args) { String a = null; boolean b = null instanceof String; boolean c = a instanceof String; System.out.println(b + " " + c); } } prints this: false false
Remember that arrays are objects, even if the array is an array of primitives. Watch for questions that look something like this: int [] nums = new int[3]; if (nums instanceof Object) { } // result is true An array is always an instance of Object. Any array
The conditional operator is a ternary operator (it has three operands) and is used to evaluate boolean expressions, much like an if statement except instead of executing a block of code, if the test is true, a conditional operator will assign a value to a variable. In other words, the basic purpose of the conditional operator is to decide which of two values to assign to a variable. This operator is constructed using a ? (question mark) and a : (colon). The parentheses are optional. Its structure is:
x = (boolean expression) ? value to assign if true : value to assign if false Let's take a look at a conditional operator in code:
class Employee { public static void main(String [] args) { int pets = 3; String status = (pets<4) sizeofyard =" 12;" numofpets =" 4;" status =" (pets<4)?"> 8)? "Pet limit on the edge" :"too many pets"; System.out.println("Pet status is " + status);
} remember that conditional operators are sometimes confused with assertion statements, so be certain you can tell the difference.
This Blog is all about Java and programming.This blog is written by Vaibhav Pandey .He is a Computer Science Graduate .You can contact the author at javatute@gmail.com for any suggestion or Query.You can also contact the author for advertising on this blog.All the material presented here is the property of author and its reproduction in any form is strictly prohibited.
Disclaimer:-Download links provided here are not of author in any means.These are found over the Internet.