0% found this document useful (0 votes)
7 views

JAVA Demo

Uploaded by

keshav
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

JAVA Demo

Uploaded by

keshav
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

INDEX

1. History and Introduction of Java ------------------------------- 1-10


2. First Java Application ----------------------------------------- 11-17
3. Java Fundamentals: Identifiers --------------------------------- 18-20
4. Java Fundamentals: Keywords / Reserved Words ----------------- 21-23
5. Java Fundamentals: Data Types -------------------------------- 24-28
6. Java Fundamentals: Literals / Constants ------------------------ 29-33
7. Java Fundamentals: Arrays ------------------------------------ 34-43
8. Java Fundamentals: Types of Variables ------------------------- 44-51
9. Java Fundamentals: var-arg Methods --------------------------- 52-55
(Variable Number of Argument Methods)
10. Java Fundamentals: Command Line arguments ------------------ 56-59
11. Java Fundamentals: Java Coding Standards --------------------- 60-62
12. Operators in Java --------------------------------------------- 63-77
13. Java Program Format ----------------------------------------- 78-83
14. import Statemen --------------------------------------------- 84-92
15. Packages in Java --------------------------------------------- 93-102
16. Access Modifiers in Java -------------------------------------- 103-118
17. Flow Controls in Java ----------------------------------------- 119-134
18. Exception Handling ------------------------------------------- 135-160
19. OOP’s Concepts: OOP’s Vs Others ------------------------------ 161-164
20. OOP’s Concepts: Data Hiding (Abstraction and Encapsulation) --- 165-173
21. OOP’s Concepts: Containers in Java ---------------------------- 174-183
22. OOP’s Concepts: Methods in java ------------------------------ 184-191
23. OOP’s Concepts: Object in java -------------------------------- 192-202
24. OOP’s Concepts: Constructors in Java -------------------------- 203-223
25. OOP’s Concepts: Instance Context ----------------------------- 224-229
26. OOP’s Concepts: this Keyword --------------------------------- 230-237
27. OOP’s Concepts: static Keyword ------------------------------- 238-253
28. OOP’s Concepts: final Keyword --------------------------------- 254-260
29. Java Fundamentals: Main Method ------------------------------ 261-269
30. OOP’s Concepts: Relationships in Java -------------------------- 270-292
31. OOP’s Concepts: Inheritance ----------------------------------- 293-300
32. OOP’s Concepts: super Keyword -------------------------------- 301-306
33. OOP’s Concepts: Object Type Casting (non-primitive type casting) - 307-313
34. OOP’s Concepts: Polymorphism -------------------------------- 314-330
35. OOP’s Concepts: Coupling & Cohesion -------------------------- 331-333
36. OOP’s Concepts: Interfaces ------------------------------------ 334-348
37. OOP’s Concepts: Object Cloning -------------------------------- 349-354
38. Multi Threading ---------------------------------------------- 355-386
39. Inner Classes ------------------------------------------------- 387-402
40. Java.lang Package: Object Class -------------------------------- 403-415
41. Java.lang Package: String, StringBuffer, and StringBuilder -------- 416-430
42. Java.lang Package: Wrapper Classes ---------------------------- 431-436
43. Java.lang Package: Autoboxing and Unboxing -------------------- 437-443
44. java.io Package ----------------------------------------------- 444-468
45. Serialization -------------------------------------------------- 469-472
46. Collections Framework ---------------------------------------- 473-491
47. Generics ----------------------------------------------------- 492-494
48. Enum -------------------------------------------------------- 495-496
49. Networking in Java ------------------------------------------- 497-499
50. RMI (Remote Method Invocation) ------------------------------ 500-501
51. GUI (Graphical User Interface) -------------------------------- 502-509
52. Garbage Collection -------------------------------------------- 510-512
Operators in Java

List of Operators:- y = --x; 10 9 9


1. Increment and Decrement Operators y = x--; 10 10 9
2. Arithmetic Operators Ex : int x = 10;
3. String Concatenation Operator int y = ++x;
4. Relational Operators System.out.println(y); // 11
5. equality Operators Ex : int x = 10;
6. instanceof Operator int y = ++10;
7. bitwise operators System.out.println(y); // CTE: error: unexpected type
8. short circuit Operators (required: variable, found: value)
9. Type Cast Operators ▪ We can apply increment and decrement
10. Assignment Operators operators, only for variable but not for the
11. Conditional Operators literals.
12. new Operator ▪ If we try to apply Increment or decrement
13. [ ] Operators operator on literal then we will get the CTE:
14. Operator Precedence required: unexpected type (variable, found:
15. Evaluation Order of operands value).
16. new Vs newInstance() Ex : int x = 10;
17. ClassNoFoundException Vs NoClassDeFoundError int y = ++(++x);
18. instanceof Vs isInstance() System.out.println(y); // CTE: required: unexpected
type (variable, found: value).
1. Increment & Decrement Operators :-
Ex : final int x =10;
a. Increment Operators :-
x++;
i. Pre – Increment Operator
System.out.println(x); // Cannot assign a value to
Ex : a = ++b;
final variable
ii. Post – Increment Operator
▪ We cannot use increment or decrement operators
Ex : a = b++;
with final variables.
b. Decrement Operators :-
Ex : int i = 10;
i. Pre – Decrement Operator
++i;
Ex : a = --b;
system.out.println(i); // 11
ii. Post – Decrement Operator Ex : char ch = ‘a’;
Ex : a = b--; ++ch;
Expression Initial Value Final Value system.out.println(ch); // b
Value of x of y of x Ex : double d = 10.5;
y = ++x; 10 11 11 d++;
y = x++; 10 10 11 system.out.println(d); // 11.5
63
Ex : boolean b = true; Infinity :-
b++; Ex-1 : Note:- In integral data types (byte, short,
system.out.println(b); // CTE: Operator ++ cannot int, long) there is no way to represent infinity.
be applied to boolean Hence if infinity is the result, we will get arithmetic
▪ Except Boolean data type, increment and exception (/ by zero) in integral data types.
decrement operators are valid for all the primitive System.out.println(10/0); // RTE: / by zero
data types. Ex-2 : In floating point data types (Float & double),
Ex : byte b = 10; there is a way to represent infinity. For this Float
b = b+1; // Use type casting for solution and Double classes contains the following two
system.out.println(d); // CTE: Cannot convert int to constents POSITIVE_INFINITY and
byte NEGATIVE_INFINITY. Hence even though result is
or infinity, we would not get any Arithmetic Exception
Ex : byte b1 = 10; in floating point data types.
byte b2 = 20; System.out.println(10/0.0); // Infinity
byte b3 = b1+b2; // Use type casting to solve System.out.println(10.0/0.0); // Infinity
system.out.println(b3); // CTE: Cannot convert int System.out.println(10.0/0); // Infinity
to byte System.out.println(10/0.0); // -Infinity
▪ If we apply any arithmetic operator between two System.out.println(10.0/0.0); // -Infinity
variables a and b, the result type is always System.out.println(10.0/0.0); // -Infinity
max(int, type of a, type of b). In cmd:- type java.java.lang.Double, you will see their
2. Arithmetic Operators :- POSITIVE_INFINITY and NEGATIVE_INFINITY
▪ If we apply any arithmetic operator between two Variable there.
variables a & b, the result always is always Ex-3 : In integral data types (byte, short, int, long),
max(int, type of a, type of b). there is no way to represent undefined results. Hence
if the result is undefined we will get run time
exception saying Arithmetic exception(/ by zero);
System.out.println(0/0); // RTE: / by zero

Ex-4 : NaN(Not a Number):- In floating point


Ex : byte + byte = int
data types (float & double), there is a way to
byte + short = int
represent undefined results. For this Float and
short + short = int
Double classes contains NaN constant. Hence if the
byte + long = long
result is undefined, we would not get any Arithmetic
long + double = double
exception in floating point data types.
float + long = float
System.out.println(0.0/0); // NaN
char + char = int
System.out.println(-0.0/0); // NaN
char + double = double
Ex-5 : Note:- for any x including NaN, the following
Ex : System.out.println(‘a’ + ’b’); // 195
expressions returns false.
System.out.println(‘a’ + 7.83); // 104.83
x < NaN // false
64
x <= NaN // false Ex-1 : String a = “Java”;
x > NaN // false int b = 10, c = 20, d = 30;
x >= NaN // false System.out.println(a+b+c+d); // Java102030
x == NaN // false System.out.println(b+c+d+a); // 60Java
Note:- for any x value including NaN. The following System.out.println(b+c+a+d); // 30Java30
expression returns true. System.out.println(b+a+c+d); // 10Java2030
x != Nan//true Ex-2 : Which of the following expressions are valid?
Some more Examples of NaN:- String a = “Java”;

System.out.println(10 < Float.NaN); // false int b = 10, c = 20, d = 30;

System.out.println(10 <= Float.NaN); // false a = b+c+d; // RTE: Incompatible Type

System.out.println(10 > Float.NaN); // false (found: int, required: java.lang.String)

System.out.println(10 >= Float.NaN); // false a = a+b+c; // Valid

System.out.println(10 == Float.NaN); // false b = a+c+d; // RTE: Incompatible Type

System.out.println(Float.NaN == Float.NaN); // (found: java.lang.String, required: int)

false b = b+c+d; // Valid

System.out.println(10 != Float.NaN); // true 4. Relational Operators (<, <=, >, >=):-


System.out.println(Float.NaN !=Float.NaN); // ▪ We can apply relational operators for every
true primitive type except boolean.

Arithmetic Exception :- Ex :

▪ It is Run Time Exception but not Compile Time System.out.println(10 < 20); // true

Error. System.out.println(‘a’ > 10); // true

▪ It is possible only in integral data types but not System.out.println(‘a’ < 97.23); // true

in floating point data types. System.out.println(‘a’ > ‘A’); // true

▪ The only operators which cause Arithmetic System.out.println(true > false); // CTE:

Exception are / and %. Operator > cannot be applied to Boolean,Boolean.


▪ We cannot apply relational opraators for object
3. String Concatenation Operator (+):-
types.
▪ The only overloaded operator in java is + operator.
Ex : System.out.println(“Java” > “JDK”); // CTE:
▪ Sometimes it access arithmetic addition operator
Operator > cannot be applied to java.lang.String,
and some time it access string concatenation
java.lang.String.
operator.
▪ Nesting of relation operators are not allowed
▪ Now, the question is when concatenate operator
otherwise we will get compile time error.
works and when + operators works?
Ex : System.out.println(10<20); // true
Solution:-
System.out.println(10<20<30);// true>30 :- CTE:-
If at least one argument is string type than +
Operator > cannot be applied to Boolean,int
operator access concatenation operator, and if
both arguments are number type than + operator 5. Equality Operators (==, !=):-
access arithmetic addition operator. For Primitive Types:-
65
▪ We can apply equality operators for every parent to child or same type). Otherwise we will get
primitive types including boolean type also. compile time error saying in comparable types.
Ex : System.out.println(10 == 20); // false Thread t = new Thread();
System.out.println(‘a’ == ‘b’); // false Object o = new Object();
System.out.println(‘a’ == 97.0); // true String s = new String(“Java”);
System.out.println(false == false); // true System.out.println(t==0); // false
System.out.println(s==0); // false
For Objects:-
System.out.println(t==s); // CTE:
▪ We can apply equality operators for object types
Incomparable types: java.lang.String and
also.
java.lang.Thread
▪ For Object reference r1, r2.
▪ r1 == r2 returns true if and only if both
references pointing to the same object
(reference comparison or address comparison.
Ex :

Difference between == Operator && equals


method :-
r1 == r2 // true :-
In general we can use == operator for reference
Ex-1 :
comparison(Address comparison) and .equals()
Thtead t1 = new Thread();
method for content comparison.
Thtead t2 = new Thread();
Ex : String s1 = new String(“Java”);
Thtead t3 = t1;
String s2 = new String(“Java”);
System.out.println(t1 == t2); // false
String s3=s2;
System.out.println(t1 == t3); // true
System.out.println(s3==s2); // true
System.out.println(s1==s2); // false
System.out.println(s1.equals(s2)); // true
Note:- for any object reference r.
r == null is always false.
But null == null is true always.
Ex-1 : String s = new String(“Java”);
System.out.println(s == null); // false
Ex-2 : Ex-2 : String s = null;
Note:- If we apply equality operators for object types System.out.println(s == null); // true
than compulsory there should be some relation Ex-3 : System.out.println(null = =null); true
between argument types(either child to parent or 6. instanseof Operator :-
66
We can use instance of operator to check wheatear 2. | (OR Bitwise Operator):- Returns true if at
the given object is of particular type or not. least one argument is true.
Syntax:- 3. ^ (XOR Bitwise Operator):- Returns true if
ObjectReference instanceof Class/Interface and only if both arguments are different.
Ex-1 : Suppose we have an ArrayList by name l, we Ex-1 : In the case of Boolean it will produce answer
have different objects of different data types stored in true or false form.
in it. So, if we want to get the type name then we System.out.println(true & false); // false
will use instanceof Operator.
System.out.println(true | false); // true
Object o = l.get[0];
System.out.println(true ^ false); // true
if(o instanceof Student)
Ex-2 : In the case of Integral it will work as bitwise
{
operator.
Student s = (Student)o;
System.out.println(4 & 5); // 4
Some Code…..
} System.out.println(4 | 5); // 5

else if(o instanceof Customer) System.out.println(4 ^ 5); // 1

{ Bitwise Complement Operator (~):-


Customer c = (Student)o; ▪ We can apply this operator only for integral types
Some Code….. but not for Boolean type. If we try to apply for
} Boolean type than we will get Compile Time
Ex-2 :
Error.
Ex : In the case of Boolean it will reverse the answer.
System.out.println(~true);// CTE: Operator ~
Cannot be applied to boolean.
System.out.prinln(~4);// -5
Note:- The most significant bit access signed bit. 0
means positive number, 1 means negative number.
Thread t = new Thread();
Positive number will be represented directly in
System.out.println(t instanceof Thread); // true
memory whereas negative numbers will be
System.out.println(t instanceof Object); // true
represented indirectly in the memory in 2’s
System.out.println(t instanceof Runnable); //true
complement form.
Note:- For any class or interface, null instanceof
Class/Interface is always false. Boolean Complement Operator (!):-
System.out.println(null instanceof Thread); // false We can apply this operator only for Boolean types
System.out.println(null instanceof Runnable); //false but not for integral types.

7. Bitwise Operators(&, |, ^):- System.out.println(!7); // CTE: Operator !

1. & (AND Bitwise Operator):- Return true if cannot be applied to int


and only if both arguments are true. System.out.println(!(4>6)); // true
System.out.println(!false); // true

67
Conclusion :- Ex. 3:- Predict Output:-
▪ (&, |, ^):- Applicable for both boolean and int x=10;
integral types. if(++x<10 & x/0>15){
▪ (~):- Applicable for only integral types but not System.out.println(“Hello”);
for Boolean types. }
▪ (!):- Applicable only for boolean type but not else{
for integral type. System.out.println(“Hi”);
}
8. Short – Circuit Operators (&&,||):-
Options:-
These are exactly same as bitwise operators (&, |)
1. Compile Time Error
except the following differences.
2. Run Time Exception (/ by zero)
&,| &&, ||
3. Hello
Both arguments are Second argument is
4. Hi
compulsory to optional. Depends on
check. operator. 9. Type Cast Operator :-
Relatively Relatively performance is There are two types of type casting:-

performance is low. High. a. Implicit Type Casting

Applicable for both Applicable only with b. Explicit Type Casting

boolean and boolean but not with a. Implicit Type Casting:-


integral types. integral. ▪ Compiler is responsible to perform implicit type
Ex-1 : Use &, |, &&, || within if condition in below casting.
example ▪ Whenever we assign smaller data type value to
int x=10, y=15; bigger data type variable, implicit type casting
if(++x<10 & ++y>15){ will be performed.
x++; ▪ It is also known as widening or up-casting.
} ▪ There is no loss of information in this type
else{ casting.
y++; ▪ The following are various possible conversions
} where implicit type casting will be performed.
System.out.println(x+” “+y); // 11 17
Ex-2 :
int x=10, y=15;
if(++x<10 && ++y>15){
x++;
} Ex : int x = ‘a’;
else{ System.out.println(x); //97
y++; Note:- Compiler converts char to int automatically
} by implicit type casting.
System.out.println(x+” “+y); // 11 16 Ex : double d = 10;
68
System.out.println(d);// 10.0 Note:- We cannot perform child assignment directly
Note:- Compiler converts int to double automatically at the time of declaration.
by implicit type casting. Ex : int a=b=c=d=20;// CTE: cannot find symbol

Explicit Type Casting :- b,c,d

▪ Programmer is responsible to perform explicit Solution:- int b,c,d;

type casting. int a=b=c=d=20;// Valid


▪ Whenever we assign bigger data type value to c. Compound Assignment :-
smaller data type variable than explicit type Sometimes assignment operators mixed with some
casting is required. other operator such type of assignment operators are
▪ It is also known as narrowing or down casting. called compound assignment operators.
▪ There may be a chance of loss of information in
Ex : int a=10;
this type casting.
a+=20;
▪ The following are various possibilities where
System.out.println(a);//30
explicit type casting is required. Reverse the
The following are all possible compound assignment
below diagram. Try to move right to left.
operators in java.
+=, -+, *=, /=, %=, &=, |=, ^=, >>=, <<=
Note:- In the case of compound assignment
operators, internal type casting will be performed
automatically.
Ex : int x = 130;
Ex-1 : byte b = 10;
byte b = x; // CTE: Cannot convert from int
b = b+1;
to byte.
System.out.println(b); CTE: cannot convert
Solution:- Explicit Type Casting
from int to byte
Byte b = (byte)x;// -126
Ex : double d = 130.93; Ex-2 : byte b = 10;

int x = (int)d; b++;

System.out.println(x); // 130 (.93 will be lost) System.out.println(b);// Valid (internally b


= (byte)b+1)
10. Assignment Operators:-
Ex-3 : byte b = 127;
There are 3 types of assignment operators.
b+=3;
a. Simple Assignment:- System.out.println(b);// -126 (internally b =
Ex : int x = 10; (byte)b+1)

b. Chained Assignment:- Ex : int a, b, c, d;

Ex : int a,b,c,d; a = b = c = d = 20;


a = b = c = d = 20; a += b -= c *= d /=2;
System.out.println(a+” “+b+” “+c+” System.out.println(a+” ”+b+” “+c+” “+d); //
“+d);//20 20 20 20 -160 -180 200 10
69
11. Conditional Operator( ?: ):- vi. Bitwise Operators:-
The only possible ternary operator in java, is &
conditional operator. ^
Syntax:- result = (Condition)? True Result : False |
Result; vii. Short – Circuit Operators:-
Ex-1 : int result = (10>20)? 10 : 20; &&
System.out.println(result);// 20 ||
Ex-2 : result = (10>20)? 10 : (20>10)? 20 : 10; viii. Conditional Operators:-
System.out.println(result);// 20 ?:
ix. Assignment Operators:-
12. New Operator :-
=, +=, -=, *= …..
We can use new operator to create object.
Ex : int b = 10, c = 20, d = 40;
Ex : Test t = new Test();
int a = b+c*d/2+3;
Note:- After creating an object, constructor will be
System.out.println(a);
executed to perform initialization of an object hence
constructor is not for creation of object and it is for 15. Evaluation order of Java Operators :-
initialization of an object. ▪ In java we have only operator precedence but not

In java we have only new keyword but not delete operand precedence.
▪ Before apply any operator all operands will be
keyword because destruction of useless object is the
evaluated from left to right.
responsibility of garbage collector.
Ex : Find which method call will be evaluated first:-
13. [] Dimension Operators :- class Test
We can use this operator to declare and create {
arrays. public static void main(String[] args)
Ex : int[] x = new int[5]; {
14. Operator Precedence Table:- System.out.println(m1(1)+m1(2)*m1(3)/m1(
i. Unary Operators:- 4)+m1(5)*m1(6));
[], x++, x— }
++x, --x, ~, ! public static int m1(int n)
new, <type> {
ii. Arithmetic Operators:- System.out.print(n+” “);
*, /, % return 0;
+, - }
iii. Shift Operators:- }
>>, >>>, << Output:- 1 2 3 4 5 6 32
iv. Comparison Operators:- Solution:-
<, <=, >, >=, instanceof m1(1)+m1(2)*m1(3)/m1(4)+m1(5)*m1(6) will be
v. Equality Operators:- evaluated as below after operand evaluation.
==, != 1+2*3/4+5*6

70
1+6/4+5*6 argument). Object will be Created for
1+1+5*6 java.lang.String class.
1+1+30 Note:- forName(), getClass(), and getName() are
2+30 the members of class Class.
32 Class class:- Instances of the class Class represent

16. Difference between new V/s newInstance:- classes and interfaces in a running Java application.
▪ In the case of new operator, based on our
new Operator :-
requirement we can invoke any constructor.
we can use new operator to create an object if we
Ex : Test t = new Test();
know class name at the beginning.
Test t1 = new Test(10);
Ex : Test t = new Test();
Student s = new Student(); Test t2 = new Test(“Java”);

Customer c = new Customer(); ▪ But newInstance method internally calls no-


argument constructor. Hence to use
newInstance :-
newinstance() method, it is compulsory that
▪ newInstance is method present in class Class.
corresponding class should contain no-argument
▪ We can use newInstance() method to create
constructor otherwise we will get runtime
object, if we don’t know class name at the
exception saying InstantiationException.
beginning and it is available dynamically at run
Ex :
time.
Ex : class Student{} class Test{

class Customer{} Test(){

class Test{ System.out.println(“no-argument constructor”);

public static void main(String args[]) throws }


Exception{ public static void main(String args[]) throws
Object o = Class.forName(args[0]).newInstance(); Exception{
System.out.println(“Object Created for : Object o =
“+o.getClass().getName()); Class.forName(args[0]).newInstance();
} System.out.println(“Object Created for :
} “+o.getClass().getName());
Output :- javac Test.java }
java Test Student (It will show Student Class as }
output. Here Student is command line argument). Javac Test.java
Object will be created for Student class Java Test Test
java Test Customer (It will show Customer Class as Output:-
output. Here Customer is command line argument). no-argument constructor
Object will be Created for Customer class. Object Created for: Test
java Test java.lang.String (It will show String Class
as output. Here java.lang.String is command line

71
▪ The newInstance() method of Class class and To use new operator, To use newInstance()
Constructor class is used to create a new class is not required to method, it is compulsory
instance of the class. contain no-argument that class should have
▪ The newInstance() method of Class class can constructor. no-argument constructor
invoke zero-argument constructor only, whereas (Parameterized
newInstance() method of Constructor class can constructors are not
invoke any number of arguments. So, Constructor allowed), otherwise we
class is preferred over Class class. will get

17. Difference between ClassNotFoundException RunTimeException:


InstantiationException
V/s NoClassDefFoundException:-
At run time, if .class At run time, if .class file
▪ While using new operator, at run time of the
file not available then not available then we get
corresponding .class file is not available then we
we get RTE: RTE:
will run time exception saying:
NoClassDefFoundError ClassNotFoundException
NoClassDefFoundError:Test
Ex : Test t = new Test(); NoClassDefFoundError V/s ClassNotFound
Re: NoClassDefFoundError: Test
Exception:-
▪ At run time if Test.class file not available than
NoClassDefFoundError :-
we get run time exception saying
▪ For hard coded, class names, at run time if the
NoClassDefFoundError:Test
▪ While Using newInstance method, at run time if corresponding .class file is not available than we
will get RTE: NoClassDefFoundException, which
the corresponding .class file is not available than
we get run time exception saying is unchecked.
Ex : Test t = new Test();
ClassNotFoundException.
Ex : Object o = Class.forName(args[0]) ▪ As per above code, at run time if Test.class file

.newInstance(); is not available than we will get RTE:

Javac Test.java NoClassDefFoundException

Java Test Test123 ClassNotFoundException :-


Output:- ClassNotFoundException (If class Test123. ▪ For dynamically provided class name at run
class file is not found) runtime, if the corresponding .class file is not
new Operator newInstance() method available than we will get runtime exception
It is operator in java. It is a method present in saying: ClassNotFoundException. Which is
java.lang.Class class. checked exception.
We use new operator We us this method to Ex : Object o = Class.forName(args[0]).
to create objects if we create object if we don’t newInstance();
know the class name know the class name at Output:-
at the beginning. beginning and it is Java Test Student (Student class is missing)
available dynamically at RTE: ClassNotFoundException
run time.

72
18. Difference between instanceof V/s
isInstance :-
▪ Instanceof is an operator in java, we can use
instanceof to check whether the given object is
of a particular type or not. And we know the
type at the beginning.
Ex : Thread t = new Thread();
System.out.println(t instanceof Runnable);// true
System.out.println(t instanceof Object);// true
▪ isInstance() is method present in
java.lang.Class.
▪ we can use isInstance() method to check,
whether the given object is of particular type or
not, and we don’t know the type at the
beginning and it is available dynamically at
runtime.
Ex.:-
class Test{
public static void main(String[] args)
throws exception
{
Thread t = new Thread();
System.out.println(Class.forName(args[0]).i
sInstance(t));
}
}
Output:- Java Test Runnable (true)
Java Test String (false)

~For Revision Work~

73
Important Questions
1. Which are the logical operators? 9. What is the output of the following code snippet?
(A) && (B) || int a = 5;
(C) All of the above (D) None of the above int b = 2;
2. Which of the following operators is used to perform int c = a / b;
decrement in Java? System.out.println(c);
(A) -- (B) + (A) 2 (B) 2.5
(C) * (D) & (C) 3 (D) Compilation error
3. What is the output of the following code snippet? 10. Which of the following operators is used to perform
int a = 5; logical OR in Java?
int b = 7; (A) & (B) &&
System.out.println((a > b) ? "a is greater than b" : "a (C) || (D) ^
is less than or equal to b"); 11. Which of the following operators is used to perform
(A) a is greater than b Bitwise OR in Java?
(B) a is less than or equal to b (A) | (B) ^
(C) Compilation error (C) & (D) ||
(D) Runtime error 12. Which of the following operators is used to perform
4. Which of the following operators is used to perform equality comparison in Java?
bitwise XOR in Java? (A) = (B) ==
(A) ^ (B) | (C) != (D) >
(C) & (D) ~ 13. Which of the following operators is used to perform
5. Which of the following is a unary logical operator in Bitwise AND in Java?
Java? (A) & (B) &&
(A) ! (B) & (C) | (D) ^
(C) | (D) ^ 14. Which of the following operators is used to perform
6. What is the output of the following code snippet? modulo division in Java?
int x = 10; (A) / (B) %
int y = 20; (C) * (D) &
int z = x++ + ++y; 15. Which of the following operators has the highest
System.out.println(z); precedence in Java?
(A) 31 (B) 2 (A) + (B) /
(C) 33 (D) 34 (C) ++ (D) &&
7. Which of the following is a conditional operator in 16. Which of the following is a unary operator in Java?
Java? (A) + (B) /
(A) = (B) * (C) - (D) *
(C) + (D) ? 17. Which of the following is a logical operator in Java?
8. Which of the following operators is used to perform (A) ++ (B) /
left shift in Java? (C) && (D) =
(A) << (B) >> 18. Which of the following is a relational operator in
(C) & (D) | Java?
74
(A) + (B) = (C) The destination type can be larger or smaller than
(C) == (D) && source type
19. What is the new operator? (D) None of the mentioned
(A) Allocates memory for an object or array 28. If a variable or operand in an expression is type long,
(B) Allocates memory for an object or array and then all the operands are type promoted to which data
returns a particular pointer type?
(C) Used as return type when an object is created (A) int (B) long
(D) Used to declare any new thing in a program (C) float (D) double
20. A Java Ternary operator has priority less than ____. 29. A boolean literal in java can be type casted to which
(A) Relational operator data type?
(B) Arithmetic operator (A) byte (B) short
(C) Logical and bitwise operator (C) int (D) None of the above
(D) All 30. Which are the compatible Data Types for Type
21. State TRUE or FALSE, TRUE expression part comes promotion or Type Casting?
first after ? (question mark) symbol and before : (A) byte, int, short (B) char, int, float
(colon) symbol. (C) float, long, double (D) All of the above
(A) FALSE (B) TRUE 31. What is the output of a bitwise OR (l) operation if
(C) Nothing can be said (D) None of these both the inputs are 1s?
22. The condition of the Java ternary operator should (A) 0 (B) 1
evaluate to ____ (C) 0 or 1 both (D) None of the above
(A) 1 or 0 (B) true or false 32. What is the output of a Bitwise AND (&) operation if
(C) TRUE or FALSE (D) None both the inputs / operands are 1s?
23. Java ternary operator is sometimes called ____. (A) 0 (B) 1
(A) Relational operator (B) Conditional operator (C) 0 or 1 both (D) None of the above
(C) Logical operator (D) None 33. What is the output of the Java code snippet?
24. What is the other name for a question mark –colon (? byte a= 0b0000_0001;
:) operator in java? System.out.println(~a);
(A) Special Relational operator (A) -1 (B) -2
(B) Special Logical operator (C) 254 (D) +127
(C) Ternary operator 34. Right Shift (>>) in Java is equivalent to ?
(D) none (A) Multipying the number by 2
25. Select from among the following character escape (B) Dividing the number by 2
code which is not available in Java. (C) Subtracting the number by 2
(A) \\ (B) \v (D) Adding the number by 2
(C) \a (D) \t 35. Left Shift (<<) in Java is equivalent to?
26. Evaluate the value of the expression? (A) Subtracting the number by 2
6 - 2 + 10 % 4 + 7 (B) Dividing the number by 2
(A) 14 (B) 12 (C) Multiplying the number by 2
(C) 13 (D) 10 (D) Adding the number by 2
27. Which of these is necessary condition for automatic 36. What is this >>> bitwise operator in Java?
type conversion in Java? (A) Left shift operator
(A) The destination type is smaller than source type (B) Left Shift Fill Zero operator
(B) The destination type is larger than source type (C) Right Shift operator
75
(D) Right Shift Fill Zero operator (B) Postfix operation is carried out on the next line or
37. Instanceof returns _____ if the value of the object is statement. So the variable value will not change.
null. (C) A and B
(A) -1 (B) 1 (D) None of the above.
(C) True (D) False 44. Among the operator groups (++, --) and (+,-,*,/,%) in
38. Which of the operators can be used to concatenate Java , which group has higher priority ?
two or more string objects? (A) (++, --) group has higher priority than (+,-,*,/,%)
(A) + (B) += group.
(C) & (D) ll (B) ( ++, --) group has lower priority than (+,-,*,/,%)
39. What is the right output of this program ? group.
public class ShiftOperators { (C) ( ++,--) group and (+,-,*,/,%) group have equal
public static void main(String[] args) { priority.
System.out.print(8<<2); (D) None of the above
System.out.print(","); 45. Choose the correct statement about Java operators +,-
System.out.print(8>>1); ,*,/,%.
} (A) + and – have equal priority.
} (B) * and / have equal priority.
(A) 4, 32 (B) 32,4 (C) / and % have equal priority
(C) 16,4 (D) 4,16 (D) All of the above.
40. What is the right output of this program? 46. Among Postfix decrement and Prefix increment
public class UnaryOperators { operators in Java, which operator has less priority?
public static void main(String[] args) { (A) Postfix decrement has less priority than prefix
int i = 5; increment
System.out.print(i++); (B) Prefix increment has less priority than Postfix
System.out.print(++i); decrement
System.out.print(i--); (C) Both operators have same priority
System.out.print(--i); (D) None of the above
} 47. Between Postfix and Prefix arithmetic operators in
} Java, which operators have more priority?
(A) 6765 (B) 5654 (A) Postfix operators have more priority than Prefix
(C) 5775 (D) 5765 operators.
41. Which are the relational operators? (B) Prefix operators have more priority than Postfix
(A) < < = (B) > > = instanceof operators.
(C) Both Prefix and Postfix operators have equal
(C) = = ! = (D) All of the above
priority.
42. Which are the unary operators?
(D) None of the above.
(A) ++ (B) --
48. Arithmetic operators +,-,/,* and % which
(C) Both of the above (D) None of these
associativity?
43. Choose the correct statement about Java Prefix and (A) Right to left (B) Left to right
Postfix operations. (C) Right t right (D) Left to left
(A) Prefix operation is carried out immediately and 49. What is the output of the javacode snippet?
the variable value will be incremented or Int a=5, b=10, c=15;
decremented accordingly. a -=3;
76
b *=2; int z;
c /=5; x=3;
system.out.println(a +” “ + b + “ “ + c); y=4;
(A) 2 20 3 (B) 2 20 5 z = ++x * y++;
(C) 2 10 5 (D) -2 20 3 (A) 2 (B) 3
50. What is the output of Java code snippet? (C) 4 (D) unknown/undefined
short k=1; 56. What value does the variable z have after ALL of the
k += 2; code above executes?
system.out.println(k); int x;
(A) 1 (B) 2 int y;
(C) 3 (D) Compiler error about Typecasting. int z;
51. What is the output of the below Java code snippet? x=3;
short p=1; y=4;
z = ++x * y++;
short k=p+2;
(A) 9 (B) 12
system.out.println(k);
(C) 16 (D) 20
(A) 1 (B) 2
57. What value does the variable a have after ALL of the
(C) 3 (D) Compile error
code above executes?
52. What is the output of the below Java code snippet?
int a;
Int a= 2 -- 7;
int b;
System.out.println(a); a=1;
(A) -5 (B) 10 b=a++;
(C) 9 (D) Compile error (A) 1 (B) 2
53. With x = 0, which of the following are legal lines of (C) 3 (D) unknown/undefined
Java code for changing the value of x to 1? 58. What value does the variable b have after ALL of the
x++; code executes?
x = x + 1; int a;
x += 1; int b;
x =+ 1;
a=1;
(A) 1, 2 & 3 (B) 1 & 4
b=a++;
(C) 1, 2, 3 & 4 (D) 3 & 2
(A) 1 (B) 2
54. What value does the variable y have after ALL of the
(C) 3 (D) unknown/undefined
code above executes?
int x; Answer key
int y; 1 2 3 4 5 6 7 8 9 10
int z; C A B A A C D A A C
11 12 13 14 15 16 17 18 19 20
x=3;
A B A B C C C C B D
y=4; 21 22 23 24 25 26 27 28 29 30
z = ++x * y++; B B B C C C B B D D
(A) 4 (B) 5 31 32 33 34 35 36 37 38 39 40
(C) 6 (D) unknown/undefined B B B B C D D A B C
55. What value does the variable x have after ALL of the 41 42 43 44 45 46 47 48 49 50
D C C A D B A B A C
code above executes?
51 52 53 54 55 56 57 58
int x; D C C B C C B A
int y;
77

You might also like