[go: up one dir, main page]

0% found this document useful (0 votes)
29 views109 pages

Questions Bank

Uploaded by

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

Questions Bank

Uploaded by

Dhruti Patel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 109

Keyword:

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.

Simple a=new Simple();

● Initialization − The 'new' keyword is followed by a call to a constructor. This


call initializes the new object.

Now, let us see an example −

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).

The instanceof in java is also known as type comparison operator because it


compares the instance with type. It returns either true or false. If we apply the
instanceof operator with any variable that has null value, it returns false.

Simple example of java instanceof


Let's see the simple example of instance operator where it tests the current
class.

1. class Simple1{
2. public static void main(String args[]){

3. Simple1 s=new Simple1();


4. System.out.println(s instanceof Simple1);//true

5. }
6. }

Output : true

modulus operator :

Modulo or Remainder Operator returns the remainder of the two numbers


after division. If you are provided with two numbers, say A and B, A is the
dividend and B is the divisor, A mod B is there a remainder of the division
of A and B. Modulo operator is an arithmetical operator which is denoted
by %.
Syntax:
A % B
Where A is the dividend and B is divisor
import java.io.*;
import java.util.*;

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 :

In Java, the ternary operator is a type of Java conditional operator. In this


section, we will discuss the ternary operator in Java with proper examples.

The meaning of ternary is composed of three parts. The ternary operator (? :)


consists of three operands. It is used to evaluate Boolean expressions. The
operator decides which value will be assigned to the variable. It is the only
conditional operator that accepts three operands. It can be used instead of the
if-else statement. It makes the code much more easy, readable, and shorter.

Syntax:
1. variable = (condition) ? expression1 : expression2

Example of Ternary Operator


TernaryOperatorExample.java
1. public class TernaryOperatorExample
2. {
3. public static void main(String args[])
4. {
5. int x, y;
6. x = 20;
7. y = (x == 1) ? 61: 90;
8. System.out.println("Value of y is: " + y);
9. y = (x == 20) ? 61: 90;
10. System.out.println("Value of y is: " + y);
11. }
12. }

Output

Value of y is: 90
Value of y is: 61

Bitwise operators :

Bitwise Operators

Bitwise operators are used to perform the manipulation of individual bits of


a number. They can be used with any integral type (char, short, int, etc.).
They are used when performing update and query operations of the Binary
indexed trees.
Now let’s look at each one of the bitwise operators in Java:
1. Bitwise OR (|)
This operator is a binary operator, denoted by ‘|’. It returns bit by bit OR of
input values, i.e., if either of the bits is 1, it gives 1, else it shows 0.
Example:
a = 5 = 0101 (In Binary)
b = 7 = 0111 (In Binary)

Bitwise OR Operation of 5 and 7


0101
| 0111
________
0111 = 7 (In decimal)
2. Bitwise AND (&)
This operator is a binary operator, denoted by ‘&.’ It returns bit by bit AND
of input values, i.e., if both bits are 1, it gives 1, else it shows 0.
Example:
a = 5 = 0101 (In Binary)
b = 7 = 0111 (In Binary)

Bitwise AND Operation of 5 and 7


0101
& 0111
________
0101 = 5 (In decimal)
3. Bitwise XOR (^)
This operator is a binary operator, denoted by ‘^.’ It returns bit by bit XOR
of input values, i.e., if corresponding bits are different, it gives 1, else it
shows 0.
Example:
a = 5 = 0101 (In Binary)
b = 7 = 0111 (In Binary)

Bitwise XOR Operation of 5 and 7


0101
^ 0111
________
0010 = 2 (In decimal)
4. Bitwise Complement (~)
This operator is a unary operator, denoted by ‘~.’ It returns the one’s
complement representation of the input value, i.e., with all bits inverted,
which means it makes every 0 to 1, and every 1 to 0.
Example:
a = 5 = 0101 (In Binary)
Bitwise Complement Operation of 5

~ 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

// Java program to illustrate


// bitwise operators

public class operators {


public static void main(String[] args)
{
// Initial values
int a = 5;
int b = 7;

// 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

Prefix and postfix increment operator :

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.

Postfix Increment Operators

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;

public class PostfixIncrementOperator {


public static void main(String[] args) {
int a = 6;
int b = 0;
System.out.println("a value is " + a);
System.out.println("b value is " + b);

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

Prefix Increment Operators

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;

public class PrefixIncrementOperator {


public static void main(String[] args) {
int a = 6;
int b = 0;

System.out.println("a value is " + a);


System.out.println("b value is " + b);

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:

“Class” in-built class

Java Class class


Java Class class instances represent the classes and interfaces in a running
java application. Every Array belongs to a class is a Class object and it is shared
by all arrays (with same element type and number of dimensions).

Methods
Method Description

asSubclass(Class<U> clazz) It casts this Class object to


represent a subclass of the class
represented by the given class
object.

cast(Object obj) It casts an object to the class or


interface represented by this Class
object.

desiredAssertionStatus() It returns the assertion status that


would be assigned to this class if it
was to be initialized at the time
when this method is called.

forName(String className) It returns the Class object


associated with the class or
interface with the specified string
name.

forName(String name, boolean It returns the Class object


initialize,ClassLoader loader) associated with the class or
interface with the specified string
name, using the given class loader.
getAnnotatedInterfaces() It returns an array of Annotated
Type objects that represents the use
of types to specify super interfaces
of the entity represented by this
Class object.

getAnnotatedSuperclass() It returns an Annotated Type object


that represents the usage of a type
to specify the superclass of the
entity as represented by this Class
object.

getAnnotation(Class<A> This method returns this element's


annotationClass) annotation for the given type, if such
an annotation is present, else it
returns null.

getAnnotations() This method returns annotations


that are present on this element.

getAnnotationsByType(Class<A>an This method returns annotations


notationClass) that are associated with this
element.
getCanonicalName() It returns the canonical name of the
underlying class as defined by the
Java Language Specification.

getClasses() It returns an array containing Class


objects representing all the public
interfaces and classes that are
members of the class and are
represented by this Class object.

getClassLoader() This method returns the class loader


for the class.

getComponentType() This method returns the Class


representing the component type of
an array.

getConstructor(Class<?>... It returns a Constructor object that


parameterTypes) reflects the specified public
constructor of the class represented
by this Class object.
getConstructors() It returns an array which contains
the Constructor's objects reflecting
all the public constructors of the
class represented by this Class
object.

getDeclaredAnnotation(Class<A>an It returns this element's annotation


notationClass) for the specified type if such an
annotation is directly present, else it
returns null.

getDeclaredAnnotations() It returns annotations that are


present on this element.

getDeclaredAnnotationsByType(Cla It returns this element's


ss<A> annotationClass) annotation(s) for the specified type
if such annotations are either
directly or indirectly present.
getDeclaredClasses() It returns an array of Class objects
reflecting all the interfaces and
classes which are declared as the
members of the class represented
by this Class object.

getDeclaredConstructor(Class<?>... It returns a Constructor object that


parameterTypes) reflects the given constructor of the
class or interface represented by the
Class object.

getDeclaredConstructors() It returns an array of Constructor


objects reflecting all the
constructors declared by the class
represented by this Class object.

getDeclaredField(String name) It returns a Field object that reflects


the declared field of the class or
interface represented by the Class
object.
getDeclaredMethod(String name, It returns a Method object that
Class<?>... parameterTypes) reflects the given declared method
of the class or interface as
represented by this Class object.

getDeclaringClass() It returns the class or interface


represented by this Class object
(which is a member of another
class) and the Class object
representing the class in which it
was declared.

getEnclosingClass() It returns the immediately enclosing


class of the underlying class.

getEnclosingConstructor() If the invoked Class's object


represents a local or anonymous
class within a constructor then it
returns a Constructor object
representing the immediately
enclosing constructor of the
underlying class.
getEnclosingMethod() If the invoked Class object
represents a local or anonymous
class within a method then it returns
a Method object which represents
the immediately enclosing method
of the underlying class.

getEnumConstants() It returns the elements of this enum


class or null if this Class object does
not represent an enum type.

getField(String name) It returns a Field object that reflects


the specified public member field of
the interface or class represented by
this Class object.

getFields() It returns an array containing Field


objects reflecting all the accessible
public fields of the interface or class
represented by this Class object.
getGenericInterfaces() Returns the Types representing the
interfaces directly implemented by
the class or interface represented by
this object

getGenericSuperclass() Returns the Type representing the


direct superclass of the entity (class,
interface, primitive type or void)
represented by this Class.

getInterfaces() It determines the interfaces


implemented by the interface or
class represented by this object.

getMethod(String name, Class<?>... It returns a method object that gives


parameterTypes) the specified public
member method of the interface or
class represented by this Class
object
getMethods() It returns an array containing
Method objects reflecting all the
public methods of the class or
interface represented by this Class
object. It also includes the declared
methods of the class or interface
and those inherited from super
classes and super interfaces

getModifiers() It returns the Java language


modifiers for this class or interface,
encoded in an integer.

getName() It returns the name of the entity


represented by this Class object, as
a String.

getPackage() It simply gets the package for this


class.

getProtectionDomain() It returns the Protection Domain of


this class.
getResource(String name) This method searches for a
resource with the given name.

getResourceAsStream(String name) This method searches for a


resource with a given name.

getSigners() It returns the signers of this class.

getSimpleName() This method returns the name of the


underlying class as given in the
source code.

getSuperclass() This method returns the Class which


represents the superclass of the
entity represented by this Class.

getTypeName() This method returns an informative


string for the name of this type.
getTypeParameters() It returns an array of Type Variable
objects that represent the type
variables declared by the generic
declaration represented by this
Generic Declaration object, in
declaration order.

isAnnotation() This method returns a Boolean value


'true' if this Class object represents
an annotation type.

isAnnotationPresent(Class<? This method returns a Boolean value


extendsAnnotation> 'true' if an annotation is present on
annotationClass) this element, else it returns false.

isAnonymousClass() This method returns a Boolean value


'true' if and only if the underlying
class is an anonymous class.

isArray() This method determines if this


Class object represents an array
class.
isAssignableFrom(Class<?> cls) This method checks if the interface
or class represented by this Class
object is either same, or is a
superclass or super interface of the
class or interface represented by the
given Class parameter.

isEnum() It returns a Boolean value 'true' if


and only if this class was declared
as an enum in the source code.

isInstance(Object obj) It checks if the specified Object is


assignment-compatible with the
object represented by this Class.

isInterface() It checks if the given Class object


represents an interface type.

isLocalClass() This method returns a Boolean value


'true' if the underlying class is a local
class.
isMemberClass() This method returns a Boolean value
'true' if the underlying class is a
member class.

isPrimitive() This method checks if the specified


Class object represents a primitive
type or not.

isSynthetic() This method returns a Boolean value


'true' if this class is a synthetic class
else it returns false.

newInstance() This method creates a new instance


of the class represented by this
Class object.

toGenericString() This method returns a string


describing this Class, including
information about modifiers and the
type arguments.

toString() This method converts the object to a


string.

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:

Class represented by class1: class java.lang.String


Class represented by class2: int
is p instance of String : true
is j instance of String : fal
“Object” super class
Object class in Java
The Object class is the parent class of all the classes in java by default. In other
words, it is the topmost class of java.

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:

1. Object obj=getObject();//we don't know what object will be returned from


this method

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

How to find Nth Highest Salary in SQL


Methods of Object class
The Object class provides many methods. They are as follows:

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.

public int hashCode() returns the hashcode number for this


object.

public boolean equals(Object obj) compares the given object to this


object.

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 notify() wakes up single thread, waiting on


this object's monitor.

public final void notifyAll() wakes up all the threads, waiting on


this object's monitor.

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).

public final void wait()throws causes the current thread to wait,


InterruptedException until another thread notifies (invokes
notify() or notifyAll() method).

protected void finalize()throws is invoked by the garbage collector


Throwable before object is being garbage
collected.
“String” class

Java String
In Java

, string is basically an object that represents sequence of


char values. An array
of characters works same as Java string. For example:
1. char[] ch={'j','a','v','a','t','p','o','i','n','t'};
2. String s=new String(ch);

is same as:

1. String s="javatpoint";

Java String class provides a lot of methods to perform operations on strings


such as compare(), concat(), equals(), split(), length(), replace(), compareTo(),
intern(), substring() etc.

The java.lang.String class implements Serializable, Comparable and


CharSequence interfaces

.
33.3M
722

Exception Handling in Java - Javatpoint


Next

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.

The Java String is immutable which means it cannot be changed. Whenever we


change any string, a new instance is created. For mutable strings, you can use
StringBuffer and StringBuilder 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.

How to create a string object?


There are two ways to create 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".

Why Java uses the concept of String literal?


To make Java more memory efficient (because no new objects are created if it
exists already in the string constant pool).

2) By new keyword
1. String s=new String("Welcome");//creates two objects and one reference
variable

In such case, JVM


will create a new string object in normal (non-pool) heap
memory, and the literal "Welcome" will be placed in the
string constant pool. The variable s will refer to the object
in a heap (non-pool).

Java String Example


StringExample.java

1. public class StringExample{


2. public static void main(String args[]){
3. String s1="java";//creating string by Java string literal
4. char ch[]={'s','t','r','i','n','g','s'};
5. String s2=new String(ch);//converting char array to string
6. String s3=new String("example");//creating Java string by new keyword
7. System.out.println(s1);
8. System.out.println(s2);
9. System.out.println(s3);
10.}}

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.

Java String class methods


The java.lang.String class provides many useful methods to perform operations
on sequence of char values.
N Method Description
o.

1 char charAt(int index) It returns char value for


the particular index

2 int length() It returns string length

3 static String format(String format, It returns a formatted


Object... args) string.

4 static String format(Locale l, String It returns formatted string


format, Object... args) with given locale.

5 String substring(int beginIndex) It returns substring for


given begin index.

6 String substring(int beginIndex, int It returns substring for


endIndex) given begin index and end
index.

7 boolean contains(CharSequence s) It returns true or false


after matching the
sequence of char value.

8 static String join(CharSequence It returns a joined string.


delimiter, CharSequence... elements)

9 static String join(CharSequence It returns a joined string.


delimiter, Iterable<? extends
CharSequence> elements)
10 boolean equals(Object another) It checks the equality of
string with the given
object.

11 boolean isEmpty() It checks if string is


empty.

12 String concat(String str) It concatenates the


specified string.

13 String replace(char old, char new) It replaces all


occurrences of the
specified char value.

14 String replace(CharSequence old, It replaces all


CharSequence new) occurrences of the
specified CharSequence.

15 static String equalsIgnoreCase(String It compares another


another) string. It doesn't check
case.

16 String[] split(String regex) It returns a split string


matching regex.

17 String[] split(String regex, int limit) It returns a split string


matching regex and limit.

18 String intern() It returns an interned


string.
19 int indexOf(int ch) It returns the specified
char value index.

20 int indexOf(int ch, int fromIndex) It returns the specified


char value index starting
with given index.

21 int indexOf(String substring) It returns the specified


substring index.

22 int indexOf(String substring, int It returns the specified


fromIndex) substring index starting
with given index.

23 String toLowerCase() It returns a string in


lowercase.

24 String toLowerCase(Locale l) It returns a string in


lowercase using specified
locale.

25 String toUpperCase() It returns a string in


uppercase.

26 String toUpperCase(Locale l) It returns a string in


uppercase using
specified locale.

27 String trim() It removes beginning and


ending spaces of this
string.

28 static String valueOf(int value) It converts given type into


string. It is an overloaded
method.

“StringBuffer” class

Java StringBuffer Class


Java StringBuffer class is used to create mutable (modifiable) String objects.
The StringBuffer class in Java is the same as String class except it is mutable
i.e. it can be changed.

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.

Important Constructors of StringBuffer Class


Constructor Description

StringBuffer() It creates an empty String buffer with the initial


capacity of 16.

StringBuffer(String It creates a String buffer with the specified string..


str)

StringBuffer(int It creates an empty String buffer with the specified


capacity) capacity as length.
Important methods of StringBuffer class
Modifier Method Description
and Type

public append(String s) It is used to append the specified


synchronized string with this string. The append()
StringBuffer method is overloaded like
append(char), append(boolean),
append(int), append(float),
append(double) etc.

public insert(int offset, It is used to insert the specified


synchronized String s) string with this string at the
StringBuffer specified position. The insert()
method is overloaded like insert(int,
char), insert(int, boolean), insert(int,
int), insert(int, float), insert(int,
double) etc.

public replace(int It is used to replace the string from


synchronized startIndex, int specified startIndex and endIndex.
StringBuffer endIndex, String str)

public delete(int It is used to delete the string from


synchronized startIndex, int specified startIndex and endIndex.
StringBuffer endIndex)
public reverse() is used to reverse the string.
synchronized
StringBuffer

public int capacity() It is used to return the current


capacity.

public void ensureCapacity(int It is used to ensure the capacity at


minimumCapacity) least equal to the given minimum.

public char charAt(int index) It is used to return the character at


the specified position.

public int length() It is used to return the length of the


string i.e. total number of
characters.

public String substring(int It is used to return the substring


beginIndex) from the specified beginIndex.

public String substring(int It is used to return the substring


beginIndex, int from the specified beginIndex and
endIndex) endIndex.

What is a mutable String?


A String that can be modified or changed is known as mutable String.
StringBuffer and StringBuilder classes are used for creating mutable strings.
“Integer”:

Java Integer Class


The Java Integer class comes under the Java.lang.Number package. This class
wraps a value of the primitive type int in an object. An object of Integer class
contains a single field of type int value.

Java Integer Methods


The Java Integer class provides several methods for converting an int to a
String and a String to an int, as well as other constants and methods dealing
with an int. The various Java Integer methods are as follows:

S Modifier Method Discription


N & Type

1) static int bitCount() It returns the number of 1-bits


in the 2's complement binary
representation of the specified
int value.

2) byte byteValue() It converts the given number


into a primitive byte type and
returns the value of integer
object as byte.

3) Static int compare() It compares two int values


numerically and returns the
result in integer equivalent.

4) Int compareTo() It compares two integer


objects numerically and
returns the result as -1, 0 or 1.

5) static int compareUnsigned() It compares two integer


objects numerically treating
the values as unsigned and
returns the result as -1, 0 or 1.

6) static decode() It decodes a String object into


Integer an Integer value.

7) static int divideUnsigned() It returns the unsigned


quotient of dividing the first
argument by the second
argument where each
argument and the result is
interpreted as an unsigned
value.

8) double doubleValue() It converts the given Integer


value and returns the result as
a double equivalent.

9) boolean equals() It compares the value of the


parameter to the value of the
current Integer object and
returns boolean ( True or False
).
10) float floatValue() It converts the given Integer
value and returns the result as
a float equivalent.

11) Static getInteger() It determines the integer value


Integer of the system property with
the specified name.

12) static int hashCode() It returns a hash code for the


given Integer.

13) static int highestOneBit() It returns int value with at


most a single one-bit, in the
position of the highest-order
("leftmost") one-bit in the
specified int value.

14) static int lowestOneBit() It eturns int value with at most


a single one-bit, in the
position of the lowest-order
("rightmost") one-bit in the
specified int value.

15) static int max() It returns the maximum value


amongst the two method
argument.

16) static int min() It returns the minimum value


amongst the two method
argument.

17) int intValue() It returns the value of the


specified number as an int.

18) long longValue() It returns the value of the


specified long object as long
equivalent.

19) static int numberOfLeadingZeros It returns the total number of


() zero bits preceding the
highest-order ("leftmost") one-
bit in the 2's complement
binary representation of the
specified int value.

20) static int numberOfTrailingZeros It returns the total number of


() zero bits following the lowest-
order ("rightmost") one-bit in
the 2's complement binary
representation of the specified
int value.

21) static int parseInt() It parses the String argument


as a signed decimal Integer
object.

22) static int parseUnsignedInt() It parses the String argument


as an unsigned decimal
Integer object.

23) static int remainderUnsigned() It returns the unsigned


remainder from dividing the
first argument by the second
argument where each
argument and the result is
interpreted as an unsigned
value.

24) static int reverse() It returns the value obtained


by reversing the order of the
bits in the 2's complement
binary representation of the
specified int value.

25) static int reverseBytes() It returns the value obtained


by reversing the order of the
bytes in the 2's complement
binary representation of the
specified int value.

26) static int rotateLeft() It returns the value obtained


by rotating the 2's
complement binary
representation of the specified
int value left by the specified
number of bits.
27) static int rotateRight() It returns the value obtained
by rotating the 2's
complement binary
representation of the specified
int value right by the specified
number of bits.

28) short shortValue() It returns the value of this


Integer as a short type after a
primitive conversion.

29) static int signum() It returns the signum function


of the specified int value.

30) static int sum() It returns the sum by adding


two integers together as per
the + operator.

31) static toBinaryString() It returns a string


String representation of the integer
argument as an unsigned
integer in binary base 2.

32) static toHexString() It returns a string


String representation of the integer
argument as an unsigned
integer in binary base 16.

33) static toOctalString() It returns a string


String representation of the integer
argument as an unsigned
integer in binary base 8.

34) String toString() It returns a String object


representing the value of the
Number Object.

35) static toUnsignedString() It converts the argument to a


String long by an unsigned
conversion.

36) static toUnsignedLong() It returns a string


long representation of the
argument as an unsigned
decimal value.

37) static valueOf() It returns the relevant Integer


Integer Object holding the value of the
argument passed.

“Double”:

Java Double class


The Double class generally wraps the primitive type double into an object. An
object of Double class contains a field with the type 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

byteValue() It returns the value of Double as a byte


after the conversion.

compare(double d1, double It compares the two double values.


d2)

compareTo(Double another It compares two Double objects


Double) numerically.

DoubleToLongBits(double It returns the representation of the floating


value) point value provided by IEEE 754 "double
format" bit layout.

doubleToRawLongBits(double It returns the representation of the floating


value) point value provided by IEEE 754 "double
format" bit layout.

doubleValue() It returns the value of Double as a double


after the conversion.

equals(Object obj) It compares the object with the specified


object.

floatValue() It returns the float type value for the given


Double object.
hashCode() It returns the hash code for the given
Double object.

hashCode(Double value) It returns the hash code for the given


Double value.

intValue() It returns the value of Double as an int after


the conversion.

isFinite(double d) It returns true if the argument is finite


floating point. Otherwise, returns false.

isInfinite() It returns true if the double value is


infinitely large in magnitude. Otherwise,
returns false.

isInfinite(double v) It returns true if the given number is


infinitely large in magnitude. Otherwise,
returns false.

isNaN() It returns true if the double value is Not a


Number value. Otherwise, returns false.

IsNaN(double v) It returns true if the specified number is


Not a Number value. Otherwise, returns
false.

longBitsToDouble(long bits) It returns the value of type Double in


correspondence to the given bit
representation.
longValue() It returns the value of Double as a long
after the conversion.

max(double a, double b) It returns the greater of the two double


values.

min(double a, double b) It returns the smaller of the two double


values.

parseDouble(String s) It returns a new double which is initialized


by the value provided by the String.

shortValue() It returns the value of Double as a short


after the conversion.

sum(double a, double b) It adds the two values as per the +


operator.

toHexString(double d) It returns a hexadecimal string represented


by the double argument.

toString() It returns a string represented by the


Double object.

toString(double d) It returns a string represented by the


double argument.

valueOf(double d) It returns the object of Double represented


by a double value.
valueOf(String s) It returns the object of Double which holds
the double value represented by string
argument.

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:

The hashCode for the number '45.0' is given as :1078362112


The interger type value for the double '67.0' is given as :67
Is the number 'NaN' is NaN? :true
Is the number '67.0' is finite? true

“Boolean”

Java Boolean class


The Boolean class wraps a value of the primitive type boolean in an object. Its
object contains only a single field whose type is boolean.

Methods

Methods Description

booleanValue Returns a Boolean primitive for the value of this Boolean


() object.

compare() Compares two Boolean values.

compareTo() Compares this Boolean instance with another.

equals() Returns a Boolean value true if the argument is a Boolean


object that represents the same value as this object.

getBoolean() Returns a Boolean value true if the system property name is


equal to the string "true".

hashCode() Returns a hash code for the Boolean object.


logicalAnd() Returns the result of implementing logical AND operation on
the assigned boolean operands.

logicalOr() Returns the result of implementing logical OR operation on


the assigned boolean operands.

logicalXor() Returns the result of implementing logical XOR operation on


the assigned boolean operands.

parseBoolean Parses the string argument as a Boolean.


()

toString() Returns a String instance representing the specified


Boolean's value or the specified boolean.

valueOf() Returns a Boolean instance representing the specified


Boolean value or string value.

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:

Value of boolean object true is true.


b1 is true.
Logical And will return false

“Long” class

Java Long class


The Long class generally wraps the primitive type long into an object. An object
of Long class contains a field with the type Long.

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.

byteValue() It returns the value of Long as a


byte after the conversion.

compare(long x, long y) It compares the two long values.

compareTo(long another long) It compares two long objects


numerically.

compareUnsigned(long x, long y) It compares the two long values


keeping the values unsigned.

decode(String nm) It is used to decode a string into


Long.

divideUnsigned(long dividend, long It returns the unsigned quotient for


divisor) dividing the first argument by the
second.

doubleValue() It returns the value of Long as a


double after the conversion.

equals(Object obj) It compares the object with the


specified object.

floatValue() It returns the float type value for


the given Long object.
getLong(String nm) It determines the long value for the
specified name.

getLong(String nm, Long val) It returns the long value for the
specified name.

hashCode() It returns the hash code for the


given Long object.

hashCode(Long value) It returns the hash code for the


given Long value.

highestOneBit(long i) It returns a long value with at most


one single bit in the highest order.

intValue() It returns the value of Long as an


int after the conversion.

longValue() It returns the value of Long as a


long after the conversion.

lowestOneBit(long i) It returns a long value with at most


one single bit in the lowest order.

max(long a, long b) It returns the greater of the two


long values.

min(long a, long b) It returns the smaller of the two


long values.

numberOfLeadingZeroes(long i) It returns the total number of zero


bytes in the highest order.

numberOfTrailingZeroes(long i) It returns the total number of zero


bytes in the lowest order.

parseLong(CharSequence s, int It parses the CharSequence


beginIndex, int endIndex, int radix) arguementwith a specified long in
the given index

parseLong(String s) It parses the string parameter as a


signed decimal long.

parseLong(String s, int radix) It parses the string argument as a


signed long as given in the radix.

parseUnsignedLong(CharSequence s, It parses the given CharSequence


int beginIndex, int ndIndex, int radix) argument as an unsigned long in
the given radix beginning from
beginIndex and ending till
endIndex-1.

parseUnsignedLong(String s) It parses the given string argument


as an unsigned long.

parseUnsignedLong(String s, int radix) It parses the given string argument


as an unsigned long in the index
specified by the second argument.

remainderUnsigned(long dividend, long It returns the unsigned remainder


divisor) from dividing the first argument
with the second argument.

reverse(long i) It returns the value obtained by the


reversing the given order of bits in
2?s complement binary
representation.

reverseBytes(long i) It returns the value obtained by the


reversing the given order of bits in
2?s complement representation.

rotateLeft(long i, int distance) It returns the value obtained by


rotating the 2?s complement
binary representation of the given
long value by left and by the
specified number of bits.

rotateRight(long i, int distance) It returns the value obtained by


rotating the 2?s complement
binary representation of the given
long value by right and by the
specified number of bits.

shortValue() It returns the short type value for


the given Long object.

signum(long i) It returns the signum function for


the given long value.
sum(long a, long b) It adds two long values as per the
+ operator.

toBinaryString(long i) It returns the string representation


for the given long argument as an
unsigned argument with base 2.

toHexString(long i) It returns the string representation


for the given long argument as an
unsigned argument with base 16.

toOctalString(long i) It returns the string representation


for the given long argument as an
unsigned argument with base 8.

toString() It returns the string which


represents the long value.

toString(long i) It returns the string which


represents the specified long.

toString(long i, int radix) It returns the string representation


for the first argument which is
specified by the second argument.

toUnsignedString(long i) It returns the string representation


for the argument as an unsigned
decimal value.

toUnsignedString(long i, int radix) It returns the string representation


for the first argument as an
unsigned integer value in the radix.

valueOf(l) It returns a long instance which


represents the specified value.

valueOf(String s) It returns a long instance which


holds the value of specified string.

valueOf(String s int radix) It returns the Long object which


holds the value of specified string
when parsed with the radix
provided by the second argument

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”

Java Throwable class Methods


Java Throwable class provides several methods like addSuppressed(),
fillInStackTrace(), getMessage(), getStackTrace(), getSuppressed(), toString(),
printStackTrace() etc.

Method

getMessage()

getSuppressed()

getStackTrace()

fillInStackTrace()

getLocalizedMessage()

initCause()

getCause()

printStackTrace()

“Exception” class

Java Custom Exception


In Java, we can create our own exceptions that are derived classes of the
Exception class. Creating our own Exception is known as custom exception or
user-defined exception. Basically, Java custom exceptions are used to
customize the exception according to user need.

Consider the example 1 in which InvalidAgeException class extends the


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

Difference between JDK, JRE, and JVM

Why use custom exceptions?


Java exceptions cover almost all the general type of exceptions that may occur
in the programming. However, we sometimes need to create custom exceptions.

Following are few of the reasons to use custom exceptions:

● To catch and provide specific treatment to a subset of existing Java


exceptions.

● Business logic exceptions: These are the exceptions related to business


logic and workflow. It is useful for the application users or the developers
to understand the exact problem.

In order to create custom exception, we need to extend Exception class that


belongs to java.lang package.

Consider the following example, where we create a custom exception named


WrongFileNameException:

1. public class WrongFileNameException extends Exception {


2. public WrongFileNameException(String errorMessage) {
3. super(errorMessage);
4. }
5. }

“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.

Commonly used Constructors of Thread class:

● Thread()

● Thread(String name)

● Thread(Runnable r)

● Thread(Runnable r,String name)

Commonly used methods of Thread class:

1. public void run(): is used to perform action for a thread.

2. public void start(): starts the execution of the thread.JVM calls the run()
method on the thread.

3. public void sleep(long miliseconds): Causes the currently executing


thread to sleep (temporarily cease execution) for the specified number of
milliseconds.

4. public void join(): waits for a thread to die.

5. public void join(long miliseconds): waits for a thread to die for the
specified miliseconds.

6. public int getPriority(): returns the priority of the thread.

7. public int setPriority(int priority): changes the priority of the thread.

8. public String getName(): returns the name of the thread.


9. public void setName(String name): changes the name of the thread.

10. public Thread currentThread(): returns the reference of currently


executing thread.

11. public int getId(): returns the id of the thread.

12. public Thread.State getState(): returns the state of the thread.

13. public boolean isAlive(): tests if the thread is alive.

14. public void yield(): causes the currently executing thread object to
temporarily pause and allow other threads to execute.

15. public void suspend(): is used to suspend the thread(depricated).

16. public void resume(): is used to resume the suspended


thread(depricated).

17. public void stop(): is used to stop the thread(depricated).

18. public boolean isDaemon(): tests if the thread is a daemon thread.

19. public void setDaemon(boolean b): marks the thread as daemon or user
thread.

20. public void interrupt(): interrupts the 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

Exception Handling in Java - Javatpoint

● A new thread starts(with new callstack).

● The thread moves from New state to the Runnable state.

● When the thread gets a chance to execute, its target run() method will
run.

1) Java Thread Example by extending Thread class


FileName: Multi.java

1. class Multi extends Thread{


2. public void run(){
3. System.out.println("thread is running...");
4. }
5. public static void main(String args[]){
6. Multi t1=new Multi();
7. t1.start();
8. }
9. }

Output:

thread is running...
“File” class

Java File Class


The File class is an abstract representation of file and directory pathname. A
pathname can be either absolute or relative.

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

Modifi Ty Field Description


er pe

static Stri pathSeparator It is system-dependent path-


ng separator character, represented
as a string for convenience.

static cha pathSeparatorCh It is system-dependent path-


r ar separator character.

static Stri separator It is system-dependent default


ng name-separator character,
represented as a string for
convenience.

static cha separatorChar It is system-dependent default


r name-separator character.

Constructors
Constructor Description

File(File parent, It creates a new File instance from a parent abstract


String child) pathname and a child pathname string.

File(String It creates a new File instance by converting the given


pathname) pathname string into an abstract pathname.

File(String parent, It creates a new File instance from a parent


String child) pathname string and a child pathname string.

File(URI uri) It creates a new File instance by converting the given


file: URI into an abstract pathname.

Useful Methods

Modifie Method Description


r and
Type

static File createTempFile(String It creates an empty file in the


prefix, String suffix) default temporary-file directory,
using the given prefix and suffix to
generate its name.

boolean createNewFile() It atomically creates a new, empty


file named by this abstract
pathname if and only if a file with
this name does not yet exist.

boolean canWrite() It tests whether the application can


modify the file denoted by this
abstract pathname.String[]

boolean canExecute() It tests whether the application can


execute the file denoted by this
abstract pathname.

boolean canRead() It tests whether the application can


read the file denoted by this
abstract pathname.

boolean isAbsolute() It tests whether this abstract


pathname is absolute.

boolean isDirectory() It tests whether the file denoted by


this abstract pathname is a
directory.

boolean isFile() It tests whether the file denoted by


this abstract pathname is a normal
file.

String getName() It returns the name of the file or


directory denoted by this abstract
pathname.

String getParent() It returns the pathname string of


this abstract pathname's parent, or
null if this pathname does not name
a parent directory.

Path toPath() It returns a java.nio.file.Path object


constructed from the this abstract
path.

URI toURI() It constructs a file: URI that


represents this abstract pathname.

File[] listFiles() It returns an array of abstract


pathnames denoting the files in the
directory denoted by this abstract
pathname

long getFreeSpace() It returns the number of unallocated


bytes in the partition named by this
abstract path name.

String[] list(FilenameFilter It returns an array of strings naming


filter) the files and directories in the
directory denoted by this abstract
pathname that satisfy the specified
filter.

boolean mkdir() It creates the directory named by


this abstract pathname.

Java File Example 1


1. import java.io.*;
2. public class FileDemo {
3. public static void main(String[] args) {
4.
5. try {
6. File file = new File("javaFile123.txt");
7. if (file.createNewFile()) {
8. System.out.println("New File is created!");
9. } else {
10. System.out.println("File already exists.");
11. }
12. } catch (IOException e) {
13. e.printStackTrace();
14. }
15.
16. }
17. }

Output:

New File is created!

“FileReader”

Java FileReader Class


Java FileReader class is used to read data from the file. It returns data in byte
format like FileInputStream class.

It is character-oriented class which is used for file handling in java.


Java FileReader class declaration
Let's see the declaration for Java.io.FileReader class:

1. public class FileReader extends InputStreamReader

Constructors of FileReader class


Constructor Description

FileReader(String It gets filename in string. It opens the given file in read


file) mode. If file doesn't exist, it throws
FileNotFoundException.

FileReader(File It gets filename in file instance. It opens the given file in


file) read mode. If file doesn't exist, it throws
FileNotFoundException.

Methods of FileReader class


Method Description

int read() It is used to return a character in ASCII form. It returns -1 at the


end of file.

void It is used to close the FileReader class.


close()
Java FileReader Example
In this example, we are reading the data from the text file testout.txt using Java
FileReader class.

OOPs Concepts in Java

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”

Java FileWriter Class


Java FileWriter class is used to write character-oriented data to a file. It is
character-oriented class which is used for file handling in java.
Unlike FileOutputStream class, you don't need to convert string into byte array
because it provides method to write string directly.

Java FileWriter class declaration


Let's see the declaration for Java.io.FileWriter class:

1. public class FileWriter extends OutputStreamWriter

Constructors of FileWriter class


Constructor Description

FileWriter(String file) Creates a new file. It gets file name in string.

FileWriter(File file) Creates a new file. It gets file name in File object.

Methods of FileWriter class


Method Description

void write(String text) It is used to write the string into FileWriter.

void write(char c) It is used to write the char into FileWriter.

void write(char[] c) It is used to write char array into FileWriter.

void flush() It is used to flushes the data of FileWriter.

void close() It is used to close the FileWriter.


Java FileWriter Example
In this example, we are writing the data in the file testout.txt using Java
FileWriter class.

SQL CREATE TABLE

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”

Java FileInputStream Class


Java FileInputStream class obtains input bytes from a file. It is used for reading
byte-oriented data (streams of raw bytes) such as image data, audio, video etc.
You can also read character-stream data. But, for reading streams of characters,
it is recommended to use FileReader class.

Java FileInputStream class declaration


Let's see the declaration for java.io.FileInputStream class:

1. public class FileInputStream extends InputStream

Java FileInputStream class methods


Method Description

int available() It is used to return the estimated number of bytes that


can be read from the input stream.

int read() It is used to read the byte of data from the input
stream.

int read(byte[] b) It is used to read up to b.length bytes 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.

long skip(long x) It is used to skip over and discards x bytes of data


from the input stream.

FileChannel It is used to return the unique FileChannel object


getChannel() associated with the file input stream.
FileDescriptor It is used to return the FileDescriptor object.
getFD()

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.

void close() It is used to closes the stream.

Java FileInputStream example 1: read single


character
1. import java.io.FileInputStream;
2. public class DataStreamExample {
3. public static void main(String args[]){
4. try{
5. FileInputStream fin=new FileInputStream("D:\\testout.txt");
6. int i=fin.read();
7. System.out.print((char)i);
8.
9. fin.close();
10. }catch(Exception e){System.out.println(e);}
11. }
12. }

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.

FileOutputStream class declaration


Let's see the declaration for Java.io.FileOutputStream class:

1. public class FileOutputStream extends OutputStream

FileOutputStream class methods


Method Description

protected void It is used to clean up the connection with the file


finalize() output stream.

void write(byte[] ary) It is used to write ary.length bytes from the byte
array

to the file output stream.

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.

FileChannel It is used to return the file channel object associated


getChannel() with the file output stream.

FileDescriptor getFD() It is used to return the file descriptor associated with


the stream.

void close() It is used to closes the file output stream.

Java FileOutputStream Example 1: write byte


1. import java.io.FileOutputStream;
2. public class FileOutputStreamExample {
3. public static void main(String args[]){
4. try{
5. FileOutputStream fout=new FileOutputStream("D:\\testout.txt");
6. fout.write(65);
7. fout.close();
8. System.out.println("success...");
9. }catch(Exception e){System.out.println(e);}
10. }
11. }

Output:

30.5M
714

OOPs Concepts in Java

Success...
The content of a text file testout.txt is set with the data A.

testout.txt

“BufferedReader”

Java BufferedReader Class


Java BufferedReader class is used to read the text from a character-based input
stream. It can be used to read data line by line by readLine() method. It makes
the performance fast. It inherits Reader class.

Java BufferedReader class declaration


Let's see the declaration for Java.io.BufferedReader class:

1. public class BufferedReader extends Reader

Java BufferedReader class constructors


Constructor Description

BufferedReader(Reader rd) It is used to create a buffered character input


stream that uses the default size for an input
buffer.

BufferedReader(Reader rd, It is used to create a buffered character input


int size) stream that uses the specified size for an input
buffer.
Java BufferedReader class methods
Method Description

int read() It is used for reading a single character.

int read(char[] cbuf, int It is used for reading characters into a portion of
off, int len) an array.

boolean It is used to test the input stream support for the


markSupported() mark and reset method.

String readLine() It is used for reading a line of text.

boolean ready() It is used to test whether the input stream is ready


to be read.

long skip(long n) It is used for skipping the characters.

void reset() It repositions the stream at a position the mark


method was last called on this input stream.

void mark(int It is used for marking the present position in a


readAheadLimit) stream.

void close() It closes the input stream and releases any of the
system resources associated with the stream.

Java BufferedReader Example


In this example, we are reading the data from the text file testout.txt using Java
BufferedReader class.

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

Competitive questions on Structures in Hindi

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.

Step 1: Extend javafx.application.Application and override


start()

As we have studied earlier that start() method is the starting point of


constructing a JavaFX application therefore we need to first override start
method of javafx.application.Application class. Object of the class
javafx.stage.Stage is passed into the start() method therefore import this class
and pass its object into start method. JavaFX.application.Application needs to
be imported in order to override start method.

The code will look like following.

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. }

Step 2: Create a Button

A button can be created by instantiating the javafx.scene.control.Button class.


For this, we have to import this class into our code. Pass the button label text in
Button class constructor. The code will look like following.

14.4M
230

Triggers in SQL (Hindi)

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. }

Step 3: Create a layout and add button to it

JavaFX provides the number of layouts. We need to implement one of them in


order to visualize the widgets properly. It exists at the top level of the scene
graph and can be seen as a root node. All the other nodes (buttons, texts, etc.)
need to be added to this layout.

In this application, we have implemented StackPane layout. It can be


implemented by instantiating javafx.scene.layout.StackPane class. The code
will now look like following.

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. }

Step 4: Create a Scene

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.

Step 5: Prepare the Stage

javafx.stage.Stage class provides some important methods which are required


to be called to set some attributes for the stage. We can set the title of the
stage. We also need to call show() method without which, the stage won't be
shown. Lets look at the code which describes how can be prepare the stage for
the application.

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. }

Step 6: Create an event for the button

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. }

Step 7: Create the main method

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. }

The Application will produce the following output on the screen.

“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.

How to create a Button?


Button can be created by instantiating Button class. Use the following line to create
button object.

Button btn = new Button("My Button");


Adding a Button to the scene graph
To visualize the button on the screen, we must attach it to the scene object. The
following code creates a button and adds it to the scene object.

package application;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

public class ButtonTest extends Application {

@Override
public void start(Stage primaryStage) throws Exception {
// TODO Auto-generated method stub

StackPane root = new StackPane();


Button btn=new Button("This is a button");
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
Setting the Text of the Button
There are two ways of setting the text on the button.

Passing the text into the class constructor


By calling setText("text") method
Wrapping Button Text
We can wrap the text of the button into multiple lines if the text to be displayed is too
long. This can be done by calling a setter method setWrapText(boolean) on the instance
of Button class. Pass the boolean value true in the method wherever required.

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;

public class ButtonTest extends Application {

@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);

StackPane root = new StackPane();


Button btn=new Button("Button 1",img);
btn.setWrapText(true);
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 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;

public class ButtonTest extends Application {

@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);

StackPane root = new StackPane();


Button btn=new Button();
btn.setGraphic(img);
btn.setWrapText(true);
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 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;

public class LabelTest extends Application {

@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);

StackPane root = new StackPane();


Button btn=new Button();
btn.setGraphic(img);
btn.setWrapText(true);
btn.setOnAction(new EventHandler<ActionEvent>() {

@Override
publicvoid 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 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;

public class ButtonTest extends Application {

@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();

StackPane root = new StackPane();


Button btn=new Button();
btn.setEffect(shadow);
btn.setGraphic(img);
btn.setWrapText(true);
btn.setOnAction(new EventHandler<ActionEvent>() {

@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”

Java AWT TextArea


The object of a TextArea class is a multiline region that displays text. It allows the
editing of multiple line text. It inherits TextComponent class.

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.

AWT TextArea Class Declaration


public class TextArea extends TextComponent
Fields of TextArea Class
The fields of java.awt.TextArea class are as follows:

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

//importing AWT class


import java.awt.*;
public class TextAreaExample
{
// constructor to initialize
TextAreaExample() {
// creating a frame
Frame f = new Frame();
// creating a text area
TextArea area = new TextArea("Welcome to javatpoint");
// setting location of text area in frame
area.setBounds(10, 30, 300, 300);
// adding text area to frame
f.add(area);
// setting size, layout and visibility of frame
f.setSize(400, 400);
f.setLayout(null);
f.setVisible(true);
}
// main method
public static void main(String args[])
{
new TextAreaExample();
}
}
Output:

java awt textarea example 1


Java AWT TextArea Example with ActionListener
The following example displays a text area in the frame where it extends the Frame class
and implements ActionListener interface. Using ActionListener the event is generated on
the button press, where we are counting the number of character and words entered in the
text area.
TextAreaExample2.java

// importing necessary libraries


import java.awt.*;
import java.awt.event.*;
// our class extends the Frame class to inherit its properties
// and implements ActionListener interface to override its methods
public class TextAreaExample2 extends Frame implements ActionListener {
// creating objects of Label, TextArea and Button class.
Label l1, l2;
TextArea area;
Button b;
// constructor to instantiate
TextAreaExample2() {
// instantiating and setting the location of components on the frame
l1 = new Label();
l1.setBounds(50, 50, 100, 30);
l2 = new Label();
l2.setBounds(160, 50, 100, 30);
area = new TextArea();
area.setBounds(20, 100, 300, 300);
b = new Button("Count Words");
b.setBounds(100, 400, 100, 30);

// adding ActionListener to button


b.addActionListener(this);

// adding components to frame


add(l1);
add(l2);
add(area);
add(b);
// setting the size, layout and visibility of frame
setSize(400, 450);
setLayout(null);
setVisible(true);
}
// generating event text area to count number of words and characters
public void actionPerformed(ActionEvent e) {
String text = area.getText();
String words[]=text.split("\\s");
l1.setText("Words: "+words.length);
l2.setText("Characters: "+text.length());
}
// main method
public static void main(String[] args) {
new TextAreaExample2();
}
}
Output:

java awt textarea example 2

—-----------------------------------------------------------------------------------------------

Public:

Java public keyword


A Java public keyword is an access modifier. It can be assigned to variables,
methods, constructors, and classes. It is the most non-restricted type of access
modifier.

Points to remember

● The public access modifier is accessible everywhere. So, we can easily


access the public inside and outside the class and package.

● 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 program contains multiple classes, at most one class can be assigned


as public.

● If a class contain a public class, the name of the program must be similar
to the public class name.

Examples of public keyword


Example 1

Let's see an example to determine whether public variable and method is


accessible or not outside the class. Here, we also try to create an instance of
constructor outside the class.

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:

Java static keyword


The static keyword in Java is used for memory management mainly. We can
apply static keyword with variables, methods, blocks and nested classes. The
static keyword belongs to the class than an instance of the class.

The static can be:

1. Variable (also known as a class variable)

2. Method (also known as a class method)

3. Block

4. Nested class

1) Java static variable


If you declare any variable as static, it is known as a static variable.

● 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.

Advantages of static variable

It makes your program memory efficient (i.e., it saves memory).

Program of the counter without static variable


In this example, we have created an instance variable named count which is
incremented in the constructor. Since instance variable gets the memory at the
time of object creation, each object will have the copy of the instance variable. If
it is incremented, it won't reflect other objects. So each object will have the value
1 in the count variable.

Program of counter by static variable


As we have mentioned above, static variable will get the memory only once, if
any object changes the value of the static variable, it will retain its value.

2) Java static method


If you apply static keyword with any method, it is known as static method.

● 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.

Restrictions for the static method

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.

2. this and super cannot be used in static context.

3) Java static block

● Is used to initialize the static data member.

● It is executed before the main method at the time of classloading.

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:

● Invoke current class constructor


● Invoke current class method
● Return the current class object
● Pass an argument in the method call
● Pass an argument in the constructor call

Super:

The super keyword refers to superclass (parent) objects.

Usage of Java super Keyword

1. super can be used to refer immediate parent class instance variable.

2. super can be used to invoke immediate parent class method.

3. super() can be used to invoke immediate parent class constructor.

Extends:

Its used to inherit one class to another class.


Its used extend the functionality of the parent class to the child class.
Syntax:
Class super_class
{

}
Class Sub_class extend super_class
{

Implements:
abstract, final, try, catch, throw/ rethrow, throws, finally, finalize,
private, protected. synchronized

—-------------------------------------------------------------ahi thi sodhvu nai—----------------------------------------


Basics

1. Explain Features of Java.

2. Explain OOPs concept which are available in Java.

3. What is byte code.

4. Why Java is platform independent?

5. How many primitive data types are available in Java?

6. What is user-defined data type in java?

7. Explain reference variable, available in Java.

8. Declare 1-D, 2-D array in java for primary and user-defined data type.

9. Explain “new”, “instanceof” operator.

10. Explain “for-each” and for loop.

11. What is command line argument?

Class, objects, method

1. Define class and creation of objects of a class.

2. What is instance variable and static variable of a class?

3. Explain static and non-static block of a class.

4. What is method of a class?

5. Explain features of constructor.


6. Explain constructor overloading.

7. Explain method overloading.

8. How object reference is passed as parameter of a method and object reference returned
from a method?

9. How can we implement recursive method within a class to calculate X^n?

10. What is finalize() method? Why ‘delete’ operator is not available within java?

11. Explain garbage collector.

Inheritance

1. Explain single-level and multi-level inheritance.

2. How constructors are called in multi-level inheritance?

3. Explain “this”, “super” keywords.

4. How “this” is used for invocation of constructor of same class? [ref: Account class]

5. Explain method overloading.

6.

7. Explain “final” keyword.

8. What is abstract class?

9. What is abstract method?

10. What is the need to declare “abstract class”?

11. What is interface?

12. Differentiate between class, abstract class and interface.

13. What is method overriding/run-time polymorphism/ dynamic-method dispatch?

14. How “final” keyword protects to inheritance and overriding process?

15. Explain packages and different access specifiers.

Exception Handling
1. What is Exception handling?

2. Explain “try”, catch, finally, throw and throws.

3. Explain “Throwable”, “Exception”, “ArithmeticExceotion”, “NullPointerException”,


“ArrayIndexOutOfBoundsException”.

4. What is uncaught and caught exception?

5. Explain user-defined Exception class.

Multi-Threading

1. Explain “Thread” and “Runnable”.

2. Create multi-threading application, derive from Thread class/ derived from Runnable
interface.

3. Explain start(), run(), sleep(), wait(), notify(), currentThread() methods.

4. Explain thread synchronization.

File handling

1. How can we read the data from file and write into file.

2. Explain byteStream and character Stream classes available in Java.

Inner classes, Wrapper classes

3. Explain nested class, inner and anonymous classes.

1. Explain Wrapper class.

2. Explain boxing, un-boxing of objects and primitive values.

You might also like