Questions Bank
Questions Bank
Operators:
New :
The new operator is used in Java to create new objects. It can also be used to
create an array object.
Let us first see the steps when creating an object from a class −
● Declaration − A variable declaration with a variable name with an object type.
● Instantiation − The 'new' keyword is used to create the object.
Example
public class Puppy {
public Puppy(String name) {
// This constructor has one parameter, name.
System.out.println("Passed Name is : " + name );
}
public static void main(String []args) {
// Following statement would create an object myPuppy
Puppy myPuppy = new Puppy( "jackie" );
}
}
Output
Passed Name is : jackie
Instanceof :
The java instanceof operator is used to test whether the object is an instance
of the specified type (class or subclass or interface).
1. class Simple1{
2. public static void main(String args[]){
5. }
6. }
Output : true
modulus operator :
class GFG {
public static void main(String[] args)
{
// Dividend
int a = 15;
// Divisor
int b = 8;
// Mod
int k = a % b;
System.out.println(k);
}
}
Output
7
?: ternary operator :
Syntax:
1. variable = (condition) ? expression1 : expression2
Output
Value of y is: 90
Value of y is: 61
Bitwise operators :
Bitwise Operators
~ 0101
________
1010 = 10 (In decimal)
Note: Compiler will give 2’s complement of that number, i.e., 2’s
complement of 10 will be -6.
● Java
// bitwise and
// 0101 & 0111=0101 = 5
System.out.println("a&b = " + (a &
b));
// bitwise or
// 0101 | 0111=0111 = 7
System.out.println("a|b = " + (a |
b));
// bitwise xor
// 0101 ^ 0111=0010 = 2
System.out.println("a^b = " + (a ^
b));
// bitwise not
// ~0101=1010
// will give 2's complement of 1010
= -6
System.out.println("~a = " + ~a);
// can also be combined with
// assignment operator to provide
shorthand
// assignment
// a=a&b
a &= b;
System.out.println("a= " + a);
}
}
Output
a&b = 5
a|b = 7
a^b = 2
~a = -6
a= 5
In java, the prefix increment operator increases the value and then returns it to the
variable.
The postfix operators first return the variable value, then increment or reduce the
value of the variable. The prefix operators first increment or decrease the value of a
variable and then returns value of the variable.
The postfix increment operator implies that the expression is evaluated first with the
variable’s original value, and then the variable is increased. The Postfix Increment
Operator first return the variable value, then increment the value of the variable as
shown in the below example
package com.yawintutor;
b= a++;
System.out.println("a value is " + a);
System.out.println("b value is " + b);
}
}
Output
a value is 6
b value is 0
a value is 7
b value is 6
The Prefix Increment Operator first increment the value of the variable, then return
the variable value as shown in the below example. The prefix increment operator
indicates that the variable is first incremented, and then the expression is evaluated
using the variable’s new value.
package com.yawintutor;
b= ++a;
System.out.println("a value is " + a);
System.out.println("b value is " + b);
}
}
Output
a value is 6
b value is 0
a value is 7
b value is 7
[] operator :
() operator :
Keywords:
Methods
Method Description
Example 1
1. public class JavaClassExample1 {
2. public static void main(String[] args) throws ClassNotFoundException,
IllegalAccessException, InstantiationException {
3. // returns the Class object for the class with the given name
4. Class class1 = Class.forName("java.lang.String");
5. Class class2 = int.class;
6. System.out.print("Class represented by class1: ");
7. // applying toString method on class1
8. System.out.println(class1.toString());
9. System.out.print("Class represented by class2: ");
10. // applying toString() method on class2
11. System.out.println(class2.toString());
12. String s = "JavaTpoint";
13. int i = 10;
14.
15. // checking for Class instance
16. boolean b1 = class1.isInstance(s);
17. boolean b2 = class1.isInstance(i);
18. System.out.println("is p instance of String : " + b1);
19. System.out.println("is j instance of String : " + b2);
20. }
21. }
Test it Now
Output:
The Object class is beneficial if you want to refer any object whose type you
don't know. Notice that parent class reference variable can refer the child class
object, know as upcasting.
Let's take an example, there is getObject() method that returns an object but it
can be of any type like Employee,Student etc, we can use Object class reference
to refer that object. For example:
The Object class provides some common behaviors to all the objects such as
object can be compared, object can be cloned, object can be notified etc.
26.4M
562
Method Description
public final Class getClass() returns the Class class object of this
object. The Class class can further
be used to get the metadata of this
class.
protected Object clone() throws creates and returns the exact copy
CloneNotSupportedException (clone) of this object.
public String toString() returns the string representation of
this object.
public final void wait(long causes the current thread to wait for
timeout)throws the specified milliseconds, until
InterruptedException another thread notifies (invokes
notify() or notifyAll() method).
public final void wait(long causes the current thread to wait for
timeout,int nanos)throws the specified milliseconds and
InterruptedException nanoseconds, until another thread
notifies (invokes notify() or notifyAll()
method).
Java String
In Java
is same as:
1. String s="javatpoint";
.
33.3M
722
Stay
CharSequence Interface
The CharSequence interface is used to represent the sequence of characters.
String, StringBuffer
and StringBuilder
classes implement it. It means, we can create strings in
Java by using these three classes.
We will discuss immutable string later. Let's first understand what String in
Java is and how to create the String object.
What is String in Java?
Generally, String is a sequence of characters. But in Java, string is an object
that represents a sequence of characters. The java.lang.String class is used to
create a string object.
1. By string literal
2. By new keyword
1) String Literal
Java String literal is created by using double quotes. For Example:
1. String s="welcome";
Each time you create a string literal, the JVM checks the "string constant pool"
first. If the string already exists in the pool, a reference to the pooled instance
is returned. If the string doesn't exist in the pool, a new string instance is
created and placed in the pool. For example:
1. String s1="Welcome";
2. String s2="Welcome";//It doesn't create a new instance
In the above example, only one object will be created. Firstly, JVM will not find
any string object with the value "Welcome" in string constant pool that is why it
will create a new object. After that it will find the string with the value
"Welcome" in the pool, it will not create a new object but will return the
reference to the same instance.
Note: String objects are stored in a special memory area known as the "string
constant pool".
2) By new keyword
1. String s=new String("Welcome");//creates two objects and one reference
variable
Test it Now
Output:
java
strings
example
The above code, converts a char array into a String object. And displays the
String objects s1, s2, and s3 on console using println() method.
“StringBuffer” class
Note: Java StringBuffer class is thread-safe i.e. multiple threads cannot access it
simultaneously. So it is safe and will result in an order.
“Double”:
Methods:
This class is useful in providing various methods like a method which can be
used to convert a double to a String and a method which can be used to convert
a String into a double.
Methods Description
Example 1
1. public class JavaDoubleExample1 {
2. public static void main(String[] args) {
3. Double d1 = 45d;
4. Double d2 = 67d;
5. Double d3 = Double.NaN;
6. Double d4 = Double.POSITIVE_INFINITY;
7. // Returns the hashCode.
8. System.out.println("The hashCode for the number '"+d1+"' is given
as :"+ d1.hashCode());
9.
10. // Returns the integer type value.
11. System.out.println("The interger type value for the double '"+d2+"' is
given as :"+d2.intValue());
12.
13. // Returns a boolean value
14. System.out.println("Is the number '"+d3+"' is NaN? :"+d3.isNaN());
15.
16. // Check whether the number is finitwe or not.
17. System.out.println("Is the number '"+d2+"' is finite? "+d4.isInfinite());
18.
19. }
20.}
Test it Now
Output:
“Boolean”
Methods
Methods Description
Example 1
1. public class JavaBooleanExample1 {
2. public static void main(String[] args) {
3. Boolean b1= true;
4. boolean b2=false;
5. //assigning boolean value of b1 to b3
6. Boolean b3= b1.booleanValue();
7. String str1 = "Value of boolean object "+b1+" is "+b3+".";
8. System.out.println(str1);
9. //compare b1 and b2
10. int val1 = Boolean.compare(b1,b2);
11. if(val1>0){
12. System.out.println("b1 is true.");
13. }
14. else{
15. System.out.println("b2 is true");
16. }
17. // logicalAnd() with return the same result as AND operator
18. Boolean val2 = Boolean.logicalAnd(b1,b2);
19. System.out.println("Logical And will return "+val2);
20. }
21. }
Test it Now
Output:
“Long” class
Methods:
This class is useful in providing various methods like a method which can be
used to convert a double to a String and a method which can be used to convert
a String into a double.
Methods Description
bitCount(long i) It returns the number of one bits in
two?s compliment binary
representation.
getLong(String nm, Long val) It returns the long value for the
specified name.
Example 1
1. public class JavaLongExample1 {
2. public static void main(String[] args) {
3. Long x1=67l;
4. Long x2=98l;
5. Long x3=6l;
6.
7. // Compares two long values.
8. int b1 = Long.compare(x1, x2);
9. if(b1==0)
10. {
11. System.out.println("Both '"+x1+"' and '"+ x2+"' are same");
12. }
13. else if(b1>0)
14. {
15. System.out.println(x1+" is greater than "+x2);
16. }
17. else
18. {
19. System.out.println(x1+" is smaller than "+x2);
20. }
21.
22. // Returns the hashcode for the given long value.
23. System.out.println("The hashcode for the value '"+x1+"' is given
as :"+x1.hashCode());
24.
25. // Returns the value of long in the form of short.
26. short b2 = x3.shortValue();
27. System.out.println("The short value for '"+x2+"' is given as : "+b2);
28. }
29. }
Test it Now
Output:
67 is smaller than 98
The hashcode for the value '67' is given as :67
The short value for '98' is given as : 6
“Throwable”
Method
getMessage()
getSuppressed()
getStackTrace()
fillInStackTrace()
getLocalizedMessage()
initCause()
getCause()
printStackTrace()
“Exception” class
Using the custom exception, we can have your own exception and message.
Here, we have passed a string to the constructor of superclass i.e. Exception
class that can be obtained using getMessage() method on the object we have
created.
In this section, we will learn how custom exceptions are implemented and used
in Java programs.
33M
638
“Thread” class
Thread class:
Thread class provide constructors and methods to create and perform
operations on a thread.Thread class extends Object class and implements
Runnable interface.
● Thread()
● Thread(String name)
● Thread(Runnable r)
2. public void start(): starts the execution of the thread.JVM calls the run()
method on the thread.
5. public void join(long miliseconds): waits for a thread to die for the
specified miliseconds.
14. public void yield(): causes the currently executing thread object to
temporarily pause and allow other threads to execute.
19. public void setDaemon(boolean b): marks the thread as daemon or user
thread.
21. public boolean isInterrupted(): tests if the thread has been interrupted.
22. public static boolean interrupted(): tests if the current thread has been
interrupted.
“Runnable” interface
Runnable interface:
The Runnable interface should be implemented by any class whose instances
are intended to be executed by a thread. Runnable interface have only one
method named run().
1. public void run(): is used to perform action for a thread.
Starting a thread:
The start() method of Thread class is used to start a newly created thread. It
performs the following tasks:
33.3M
722
● When the thread gets a chance to execute, its target run() method will
run.
Output:
thread is running...
“File” class
The File class have several methods for working with directories and files such
as creating new directories or files, deleting and renaming directories or files,
listing the contents of a directory etc.
Fields
Constructors
Constructor Description
Useful Methods
Output:
“FileReader”
1. package com.javatpoint;
2.
3. import java.io.FileReader;
4. public class FileReaderExample {
5. public static void main(String args[])throws Exception{
6. FileReader fr=new FileReader("D:\\testout.txt");
7. int i;
8. while((i=fr.read())!=-1)
9. System.out.print((char)i);
10. fr.close();
11. }
12. }
Here, we are assuming that you have following data in "testout.txt" file:
Welcome to javaTpoint.
Output:
Welcome to javaTpoint.
“FileWriter”
FileWriter(File file) Creates a new file. It gets file name in File object.
1. package com.javatpoint;
2. import java.io.FileWriter;
3. public class FileWriterExample {
4. public static void main(String args[]){
5. try{
6. FileWriter fw=new FileWriter("D:\\testout.txt");
7. fw.write("Welcome to javaTpoint.");
8. fw.close();
9. }catch(Exception e){System.out.println(e);}
10. System.out.println("Success...");
11. }
12. }
Output:
Success...
testout.txt:
Welcome to javaTpoint.
“FileInputStream”
int read() It is used to read the byte of data from the input
stream.
int read(byte[] b, int It is used to read up to len bytes of data from the input
off, int len) stream.
protected void It is used to ensure that the close method is call when
finalize() there is no more reference to the file input stream.
Note: Before running the code, a text file named as "testout.txt" is required to be
created. In this file, we are having following content:
Welcome to javatpoint.
“FileOutputStream”
Java FileOutputStream Class
Java FileOutputStream is an output stream used for writing data to a file
If you have to write primitive values into a file, use FileOutputStream class. You
can write byte-oriented as well as character-oriented data through
FileOutputStream class. But, for character-oriented data, it is preferred to use
FileWriter
than FileOutputStream.
void write(byte[] ary) It is used to write ary.length bytes from the byte
array
void write(byte[] ary, It is used to write len bytes from the byte array
int off, int len) starting at offset off to the file output stream.
void write(int b) It is used to write the specified byte to the file output
stream.
Output:
30.5M
714
Success...
The content of a text file testout.txt is set with the data A.
testout.txt
“BufferedReader”
int read(char[] cbuf, int It is used for reading characters into a portion of
off, int len) an array.
void close() It closes the input stream and releases any of the
system resources associated with the stream.
1. package com.javatpoint;
2. import java.io.*;
3. public class BufferedReaderExample {
4. public static void main(String args[])throws Exception{
5. FileReader fr=new FileReader("D:\\testout.txt");
6. BufferedReader br=new BufferedReader(fr);
7.
8. int i;
9. while((i=br.read())!=-1){
10. System.out.print((char)i);
11. }
12. br.close();
13. fr.close();
14. }
15. }
Here, we are assuming that you have following data in "testout.txt" file:
Keep Watching
00:00/03:34
Welcome to javaTpoint.
Output:
Welcome to javaTpoint.
“Application”
Creating Our first JavaFX Application
Here, we are creating a simple JavaFX application which prints hello world on
the console on clicking the button shown on the stage.
1. package application;
2. import javafx.application.Application;
3. import javafx.stage.Stage;
4. public class Hello_World extends Application{
5.
6. @Override
7. public void start(Stage primaryStage) throws Exception {
8. // TODO Auto-generated method stub
9.
10. }
11.
12. }
14.4M
230
1. package application;
2. import javafx.application.Application;
3. importjavafx.scene.control.Button;
4. import javafx.stage.Stage;
5. public class Hello_World extends Application{
6.
7. @Override
8. public void start(Stage primaryStage) throws Exception {
9. // TODO Auto-generated method stub
10. Buttonbtn1=newButton("Say, Hello World");
11.
12. }
13.
14. }
1. package application;
2. import javafx.application.Application;
3. import javafx.scene.control.Button;
4. import javafx.stage.Stage;
5. import javafx.scene.layout.StackPane;
6. public class Hello_World extends Application{
7.
8. @Override
9. public void start(Stage primaryStage) throws Exception {
10. // TODO Auto-generated method stub
11. Button btn1=new Button("Say, Hello World");
12. StackPane root=new StackPane();
13. root.getChildren().add(btn1);
14.
15. }
16.
17. }
The layout needs to be added to a scene. Scene remains at the higher level in the
hierarchy of application structure. It can be created by instantiating
javafx.scene.Scene class. We need to pass the layout object to the scene class
constructor. Our application code will now look like following.
1. package application;
2. import javafx.application.Application;
3. import javafx.scene.Scene;
4. import javafx.scene.control.Button;
5. import javafx.stage.Stage;
6. import javafx.scene.layout.StackPane;
7. public class Hello_World extends Application{
8.
9. @Override
10. public void start(Stage primaryStage) throws Exception {
11. // TODO Auto-generated method stub
12. Button btn1=new Button("Say, Hello World");
13. StackPane root=new StackPane();
14. root.getChildren().add(btn1);
15. Scene scene=new Scene(root);
16. }
17.
18. }
we can also pass the width and height of the required stage for the scene in the
Scene class constructor.
1. package application;
2. import javafx.application.Application;
3. import javafx.scene.Scene;
4. import javafx.scene.control.Button;
5. import javafx.stage.Stage;
6. import javafx.scene.layout.StackPane;
7. public class Hello_World extends Application{
8.
9. @Override
10. public void start(Stage primaryStage) throws Exception {
11. // TODO Auto-generated method stub
12. Button btn1=new Button("Say, Hello World");
13. StackPane root=new StackPane();
14. root.getChildren().add(btn1);
15. Scene scene=new Scene(root);
16. primaryStage.setScene(scene);
17. primaryStage.setTitle("First JavaFX Application");
18. primaryStage.show();
19. }
20.
21. }
As our application prints hello world for an event on the button. We need to
create an event for the button. For this purpose, call setOnAction() on the button
and define a anonymous class Event Handler as a parameter to the method.
Inside this anonymous class, define a method handle() which contains the code
for how the event is handled. In our case, it is printing hello world on the console.
1. package application;
2. import javafx.application.Application;
3. import javafx.event.ActionEvent;
4. import javafx.event.EventHandler;
5. import javafx.scene.Scene;
6. import javafx.scene.control.Button;
7. import javafx.stage.Stage;
8. import javafx.scene.layout.StackPane;
9. public class Hello_World extends Application{
10.
11. @Override
12. publicvoid start(Stage primaryStage) throws Exception {
13. // TODO Auto-generated method stub
14. Button btn1=new Button("Say, Hello World");
15. btn1.setOnAction(new EventHandler<ActionEvent>() {
16.
17. @Override
18. publicvoid handle(ActionEvent arg0) {
19. // TODO Auto-generated method stub
20. System.out.println("hello world");
21. }
22. });
23. StackPane root=new StackPane();
24. root.getChildren().add(btn1);
25. Scene scene=new Scene(root,600,400);
26. primaryStage.setScene(scene);
27. primaryStage.setTitle("First JavaFX Application");
28. primaryStage.show();
29. }
30.
31. }
Till now, we have configured all the necessary things which are required to
develop a basic JavaFX application but this application is still incomplete. We
have not created main method yet. Hence, at the last, we need to create a main
method in which we will launch the application i.e. will call launch() method and
pass the command line arguments (args) to it. The code will now look like
following.
1. package application;
2. import javafx.application.Application;
3. import javafx.event.ActionEvent;
4. import javafx.event.EventHandler;
5. import javafx.scene.Scene;
6. import javafx.scene.control.Button;
7. import javafx.stage.Stage;
8. import javafx.scene.layout.StackPane;
9. public class Hello_World extends Application{
10.
11. @Override
12. public void start(Stage primaryStage) throws Exception {
13. // TODO Auto-generated method stub
14. Button btn1=new Button("Say, Hello World");
15. btn1.setOnAction(new EventHandler<ActionEvent>() {
16.
17. @Override
18. public void handle(ActionEvent arg0) {
19. // TODO Auto-generated method stub
20. System.out.println("hello world");
21. }
22. });
23. StackPane root=new StackPane();
24. root.getChildren().add(btn1);
25. Scene scene=new Scene(root,600,400);
26. primaryStage.setTitle("First JavaFX Application");
27. primaryStage.setScene(scene);
28. primaryStage.show();
29. }
30. publicstaticvoid main (String[] args)
31. {
32. launch(args);
33. }
34.
35. }
“Scene”
Scene
Scene actually holds all the physical contents (nodes) of a JavaFX application.
Javafx.scene.Scene class provides all the methods to deal with a scene object.
Creating scene is necessary in order to visualize the contents on the stage.
At one instance, the scene object can only be added to one stage. In order to
implement Scene in our JavaFX application, we must import javafx.scene
package in our code. The Scene can be created by creating the Scene class
object and passing the layout object into the Scene class constructor. We will
discuss Scene class and its method later in detail.
Scene Graph
Scene Graph exists at the lowest level of the hierarchy. It can be seen as the
collection of various nodes. A node is the element which is visualized on the
stage. It can be any button, text box, layout, image, radio button, check box, etc.
The nodes are implemented in a tree kind of structure. There is always one root
in the scene graph. This will act as a parent node for all the other nodes present
in the scene graph. However, this node may be any of the layouts available in
the JavaFX system.
The leaf nodes exist at the lowest level in the tree hierarchy. Each of the node
present in the scene graphs represents classes of javafx.scene package
therefore we need to import the package into our application in order to create
a full featured javafx application.
“Stage”
Stage
Stage in a JavaFX application is similar to the Frame in a Swing Application. It
acts like a container for all the JavaFX objects. Primary Stage is created
internally by the platform. Other stages can further be created by the application.
The object of primary stage is passed to start method. We need to call show
method on the primary stage object in order to show our primary stage. Initially,
the primary Stage looks like following.
However, we can add various objects to this primary stage. The objects can only
be added in a hierarchical way i.e. first, scene graph will be added to this
primaryStage and then that scene graph may contain the nodes. A node may be
any object of the user's interface like text area, buttons, shapes, media, etc.
“Button”
JavaFX Button
JavaFX button control is represented by javafx.scene.control.Button class. A button is a
component that can control the behaviour of the Application. An event is generated
whenever the button gets clicked.
package application;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
@Override
public void start(Stage primaryStage) throws Exception {
// TODO Auto-generated method stub
JavaFX Button
Setting the Text of the Button
There are two ways of setting the text on the button.
Btn.setWrapText(true);
Setting the image on the button
Button class contains a constructor which can accept graphics along with the text
displayed on the button. The following code implements image on the button.
package application;
import java.io.FileInputStream;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
@Override
public void start(Stage primaryStage) throws Exception {
// TODO Auto-generated method stub
FileInputStream input=new
FileInputStream("/home/javatpoint/Desktop/JavaFX/Images/colored_label.png");
Image image = new Image(input);
ImageView img=new ImageView(image);
}
public static void main(String[] args) {
launch(args);
}
}
Output:
JavaFX Button 1
Using setGraphic() method:
Button class also provides an instance method named setGraphic(). We have to pass the
image view object in this method. The following code implements setGraphic() method.
package application;
import java.io.FileInputStream;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
@Override
public void start(Stage primaryStage) throws Exception {
// TODO Auto-generated method stub
FileInputStream input=new
FileInputStream("/home/javatpoint/Desktop/JavaFX/Images/colored_label.png");
Image image = new Image(input);
ImageView img=new ImageView(image);
}
public static void main(String[] args) {
launch(args);
}
}
Output:
JavaFX Button 2
Button Action
Button class provides setOnAction() methodwhich is used to set the action for the button
click event. An object of the anonymous class implementing the handle() method, is
passed in this method as a parameter.
We can also pass lambda expressions to handle the events. The following code
implements the Button event.
package application;
import java.io.FileInputStream;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
@Override
public void start(Stage primaryStage) throws Exception {
// TODO Auto-generated method stub
FileInputStream input=new
FileInputStream("/home/javatpoint/Desktop/JavaFX/Images/colored_label.png");
Image image = new Image(input);
ImageView img=new ImageView(image);
@Override
publicvoid handle(ActionEvent arg0) {
// TODO Auto-generated method stub
System.out.println("Button clicked");
}
} );
}
public static void main(String[] args) {
launch(args);
}
}
Output:
JavaFX Button 3
Button Effects
We can apply the effects to a Button. The effects are provided by javafx.scene.effect
package. The following code shows how the drop shadow effect can be applied to a
button.
package application;
import java.io.FileInputStream;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.effect.DropShadow;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
@Override
public void start(Stage primaryStage) throws Exception {
// TODO Auto-generated method stub
FileInputStream input=new
FileInputStream("/home/javatpoint/Desktop/JavaFX/Images/colored_label.png");
Image image = new Image(input);
ImageView img=new ImageView(image);
DropShadow shadow = new DropShadow();
@Override
public void handle(ActionEvent arg0) {
// TODO Auto-generated method stub
System.out.println("Button clicked");
}
} );
Scene scene=new Scene(root,300,300);
root.getChildren().add(btn);
primaryStage.setScene(scene);
primaryStage.setTitle("Button Class Example");
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
Output:
JavaFX Button 4
“TextField”
“TextArea”
The text area allows us to type as much text as we want. When the text in the text area
becomes larger than the viewable area, the scroll bar appears automatically which helps
us to scroll the text up and down, or right and left.
static int SCROLLBARS_BOTH - It creates and displays both horizontal and vertical
scrollbars.
static int SCROLLBARS_HORIZONTAL_ONLY - It creates and displays only the
horizontal scrollbar.
static int SCROLLBARS_VERTICAL_ONLY - It creates and displays only the vertical
scrollbar.
static int SCROLLBARS_NONE - It doesn't create or display any scrollbar in the text
area.
Class constructors:
Sr. no. Constructor Description
1. TextArea() It constructs a new and empty text area with no text in it.
2. TextArea (int row, int column) It constructs a new text area with specified
number of rows and columns and empty string as text.
3. TextArea (String text) It constructs a new text area and displays the specified text
in it.
4. TextArea (String text, int row, int column) It constructs a new text area with the
specified text in the text area and specified number of rows and columns.
5. TextArea (String text, int row, int column, int scrollbars) It construcst a new
text area with specified text in text area and specified number of rows and columns and
visibility.
Methods Inherited
The methods of TextArea class are inherited from following classes:
java.awt.TextComponent
java.awt.Component
java.lang.Object
TetArea Class Methods
Sr. no. Method name Description
1. void addNotify() It creates a peer of text area.
2. void append(String str) It appends the specified text to the current text of
text area.
3. AccessibleContext getAccessibleContext() It returns the accessible context
related to the text area
4. int getColumns() It returns the number of columns of text area.
5. Dimension getMinimumSize() It determines the minimum size of a text
area.
6. Dimension getMinimumSize(int rows, int columns) It determines the minimum
size of a text area with the given number of rows and columns.
7. Dimension getPreferredSize()It determines the preferred size of a text area.
8. Dimension preferredSize(int rows, int columns) It determines the preferred
size of a text area with given number of rows and columns.
9. int getRows() It returns the number of rows of text area.
10. int getScrollbarVisibility() It returns an enumerated value that indicates which
scroll bars the text area uses.
11. void insert(String str, int pos) It inserts the specified text at the specified position
in this text area.
12. protected String paramString() It returns a string representing the state of
this TextArea.
13. void replaceRange(String str, int start, int end) It replaces text between the
indicated start and end positions with the specified replacement text.
14. void setColumns(int columns) It sets the number of columns for this text
area.
15. void setRows(int rows) It sets the number of rows for this text area.
Java AWT TextArea Example
The below example illustrates the simple implementation of TextArea where we are
creating a text area using the constructor TextArea(String text) and adding it to the
frame.
TextAreaExample .java
—-----------------------------------------------------------------------------------------------
Public:
Points to remember
● If you are overriding any method, overridden method (i.e., declared in the
subclass) must not be more restrictive. So, if you assign public to any
method or variable, that method or variable can be overridden to sub-
class using public access modifier only.
● If a class contain a public class, the name of the program must be similar
to the public class name.
1. class A {
2.
3. public String msg="Try to access a public variable outside the class";
4. String info;
5. public void display()
6. {
7. System.out.println("Try to access a public method outside the
class");
8. System.out.println(info);
9. }
10.
11. public A(String info)
12. {
13. this.info=info;
14. }
15.
16. }
17.
18. public class PublicExample1 {
19. public static void main(String[] args) {
20. A a=new A("Try to create the instance of public constructor outside
the class");
21. System.out.println(a.msg);
22. a.display();
23.
24. }
25. }
Output:
Void:
Static:
3. Block
4. Nested class
● The static variable can be used to refer to the common property of all
objects (which is not unique for each object), for example, the company
name of employees, college name of students, etc.
● The static variable gets memory only once in the class area at the time of
class loading.
● A static method belongs to the class rather than the object of a class.
● A static method can be invoked without the need for creating an instance
of a class.
● A static method can access static data member and can change the value
of it.
There are two main restrictions for the static method. They are:
1. The static method can not use non static data member or call non-static
method directly.
Class:
Abstract:
The abstract keyword is a non-access modifier, used for classes and methods.
Class: An abstract class is a restricted class that cannot be used to create
objects (to access it, it must be inherited from another class). Method: An
abstract method can only be used in an abstract class, and it does not have a
body.
interface
This :
Its a reference variable that refers to the current object.object calls instance variable.
Syntax : this.var|_name;
Usage:
Super:
Extends:
}
Class Sub_class extend super_class
{
Implements:
abstract, final, try, catch, throw/ rethrow, throws, finally, finalize,
private, protected. synchronized
8. Declare 1-D, 2-D array in java for primary and user-defined data type.
8. How object reference is passed as parameter of a method and object reference returned
from a method?
10. What is finalize() method? Why ‘delete’ operator is not available within java?
Inheritance
4. How “this” is used for invocation of constructor of same class? [ref: Account class]
6.
Exception Handling
1. What is Exception handling?
Multi-Threading
2. Create multi-threading application, derive from Thread class/ derived from Runnable
interface.
File handling
1. How can we read the data from file and write into file.