Você está na página 1de 93

Q No Question Option1

The ___________ operator allocates memory to an object. It also


1 returns a ____________ to that memory location in the object new, reference
variable.

2 What is the correct result of 5<<2 00101000

Which of the following statements are true with respect to Bitwise


Opeartors?
3 Statement A: The OR operator gives the result,0, if both bits are 0, else Statement A and Statement B
1 in all other cases.
Statement B: The XOR operator applied on two bits results in 0, if
exactly one bit is 1, else 0 in all other cases.

switch(){
case Expr_1://statement(s)
break;
case Expr_2://statement(s)
break;
.
4 Which is the correct syntax of switch construct? .
.
case Expr_N://statement(s)
break;
default://statement(s);
}

What is the output of following code snippet?


for(int count=0; count<10; count++){
if(count==7){
5 break; Runtime Exception
}
System.out.println(count);
}
int a[][]={{1,2},{3,4}};
for(int i=0; i<a.length; i++){
for(int j=0; j<a[i].length; j++){ Calculating total number of
6 System.out.println(a[i][j]); columns
}
}
What is the use of a[i].length in the preceeding code snippet?

predict the correct output of the following code snippet:

7 StringBuilder str=new StringBuilder("fruitsgood"); After insertion = fruits are


str.insert(6," are "); good
System.out.println("After insertion = ");
System.out.println(str.toString());

Match the following:


A. static
B. volatile
C. transient
D. final

I. This modifier is used with a variable to specify that its value is


8 updated almost every time it is accessed.
II. This modifier can be used to control serialization as it specifies the A-I, B-II, C-III, D-IV
object properties that can be excluded from serialization.
III. This modifier is applicable for methods, variables and classes. This
type of data member definition or value cannot be further replaced or
modified.
IV. This modifier is applicable for methods, variables and classes. This
modifier is used to denote those class variables and methods that
belong specifically to a class and not to any of its particular objects.

What will be the output of the following code snippet:

int i=10,j=30;
9 while(i++<--j) No output
{
}
System.out.println(i+" "+j);
Predict the correct statement of the following code snippet:

String[][] jumbleWords=new String{{"elapp","apple"},


{"argneo","orange"},{"agrspe","grapes"}};
10 System.out.println("Fruits are: "); Runtime Exception
for(String[] i: jumbleWords){
for(String j:i){
System.out.println(j);
}
}

abstract class GameConsole{


class GameConsole{ int score;
int score; public void displayScore(){
void displayScore(){
System.out.println("Displaying the computed score of played System.out.println("Displayin
game..."); g the computed score of
abstract void computeScore(); played game...");
abstract void playGame(); void computeScore();
} void playGame();
class Badminton extends GameConsole{ }
void playGame(){ class Badminton extends
System.out.println("Starting the Badminton Game..."); GameConsole{
} void playGame(){
void computeScore(){ System.out.println("Starting
System.out.println("Computing Badminton score... "); the Badminton Game...");
} }
11 }class GameDemo{ void computeScore(){
public static void main(String[] args){ System.out.println("Computi
Badminton obj1=new Badminton(); ng Badminton score... ");
obj1.playGame(); }
obj1.computeScore(); }
obj1.displayScore(); class GameDemo{
} public static void
} main(String[] args){
Badminton obj1=new
Expected output of preceeding code snippet is : Badminton();
Starting the Badminton Game... obj1.playGame();
Computing Badminton score... obj1.computeScore();
Displaying the computed score of played game... obj1.displayScore();
}
During execution the output is the Runtime exception. Predict the }
correct code snippet for the expected result.

Fill in the gap: "When two or more threads simultaneously access the
12 same variable and atleast one thread tries to write a value to the Lock Starvation
variable, it is called the _________."
Which of the following statements are true with respect to advantages
of multithreading?
Statement A: Maximizing the use of system resources by using threads,
13 which share the more than one address spaces and belong to the Statement A
multiple process.
Statement B: Simplifies the structure of complex application, such as
multimedia applications.

class MyThread implements Runnable


{
public static void main(String args[])
{ MyThread run = new
14 /* Missing code */ MyThread(); Thread th = new
} Thread(run); th.start();
public void run() {}
}
Which of the following line of code is suitable to execute the thread ?

Match the following:


A. interrupted()
B. interrupt()
C. join()
D. isAlive()

15 I. Allow a thread to wait until the thread, on which it is called, A-II, B-I, C-IV, D-III
terminates.
II. Is used to determined if the current thread has been interrupted by
another thread.
III. Is used to interrupt the execution of a thread.
IV. Is used to check the existence of a thread.

Suggest the correct answer:


Suggest the output of the following code snippet:
class DemoRunnable implements Runnable{
public void run(){
for(int i=0;i<3;i++){
System.out.println("i="+i+",
ThreadName="+Thread.currentThread().getName());
} In main() method
} i=0
} ,ThreadName=Thread-0
public class MyClass{ i=1
public static void main(String[] args) throws InterruptedException{ ,ThreadName=Thread-0
System.out.println("In main() method"); i=0
MyRunnable runnable=new MyRunnable(); ,ThreadName=Thread-1
16 Thread thread1=new Thread(runnable); i=2
Thread thread2=new Thread(runnable);
thread1.start(); ,ThreadName=Thread-0
i=1
thread1.join(); ,ThreadName=Thread-1
thread2.start(); end main() method
thread2.join(); i=2
System.out.println("end main() method"); ,ThreadName=Thread-1
}
}

int x = 0, y = 0 , z = 0 ;
17 x = (++x + y-- ) * z++; -1
What will be the value of "x" after execution ?

18 In java, _________ can only test for equality, where as _________ can switch, if
evaluate any type of the Boolean expression.

What will be the output for the code snippet?


1. public class Test{
2. int i=8;
3. int j=9;
4. public static void main(String[] args){
5. add();
19 6. 17
}
7. public static void add(){
8. int k = i+j;
9. System.out.println(k);
10. }
11. }
Predict the output of the following code snippent:
class Base{
private Base(){
System.out.print("Base");
}
}
20 public class test extends Base{ BaseDerived
public test(){
System.out.print("Derived");
}
public static void main(String[] args){
new test();
}
}

What will be the output after the following program is compiled and
executed?
public class Test{
public static void main(String args[]){
int x = 10;
x = myMethod(x--); The will compile successfully
21 System.out.print(x); and display 9 as output.
}

static int myMethod(final int x){


return x--;
}
}

Consider the following program written in Java.


class Test{
public static void main(String args[]){
int x=8;
if(x==2);
22 NumberEight NotEight
System.out.println("NumberEight");
System.out.println("NotEight");
}
}
What would the output?
Select the correct statement with respect to the following program
code.
public class TestClass{
public static void main(String[] args){ The program has a compile
double sum = 0; error because the control
23 for(double d = 0; d < 10;){ variable in the for loop
d += 0.1; cannot be of the double
sum += sum + d; type.
}
}
}

class ClassicJumble{
public void show(){
System.out.println(choice);
}
Which is the correct code snippet to create a class ClassicJumble, public void static
24 contains the show() that displays the value of the variable, choice, the main(String[] args){
show() method is called by object, obj1. ClassicJumble obj1=new
ClassicJumble();
obj1.show();
}
}

for( ; ; ){
25 Which one is not an example of infinite loop? //statement(s)
}

What will be the output of the program?


public class Test{
public static void main(String [] args){
String s1 = args[1];
String s2 = args[2];
26 String s3 = args[3]; args[2] = 2
String s4 = args[4];
System.out.print(" args[2] = " + s2);
}
}
and the command-line invocation is C:Java> java Test 1 2 3 4
Predict the correct code which will be perfectly match at "//insert code
here" and also will allow the following code to compile:
public class Test{
public static void main(String args[]){
add();
27 add(1); void add(Integer... args){}
add(1, 2);
}

// insert code here


}

Which are the correct statements regarding inner class?


1. inner class is a class whose definition appears inside the definition of
another class.
2. The regular inner class not shares all the features of members of a 1 - True, 2 - False, 3 - False, 4
28 class.
3. Annonymous inner classes are inner classes marked with the static - True
modifier.
4. A method-local inner class is defined inside method, which can be
instantiated within nthe same method.

Which are the correct statements regarding Type Casting Object?


Statement A: Upcasting is done along the class hierarchy in a direction Statement A is True,
29 from the derived class to the base class. Statement B is false
Statement B: Downcasting is done along the class hierarchy in a
direction from the base class towards the root class.

What is the output of the following code?


public class Test{
public static void main(String args[]){
double[] myList = {1, 5, 5, 5, 5, 1};
double max = myList[0];
int indexOfMax = 0;
for(int i = 1; i < myList.length; i++){
30 if(myList[i] > max){ 0
max = myList[i];
indexOfMax = i;
}
}
System.out.println(indexOfMax);
}
}
Predict the output of the following code snippet:
public class Tester{
static int x = 4;
public Tester(){
System.out.print(this.x); // line 1
Tester(); Compile error at line 1 (static
}
31 public static void Tester(){ // line 2 x must be only accessed
inside static methods)
System.out.print(this.x); // line 3
}
public static void main(String... args){ // line 4
new Tester();
}
}

What will be the output of the following code snippet?


class Base{
int value = 0;
Base(){
addValue();
}
void addValue(){
value += 10;
}
int getValue(){
return value;
}
}
32 class Derived extends Base{ 10
Derived(){
addValue();
}
void addValue(){
value += 20;
}
}
public class Test{
public static void main(String[] args){
Base b = new Derived();
System.out.println(b.getValue());
}
}
What will be the output of the program?
class PassClass
{
public static void main(String [] args)
{
PassClass p = new PassClass();
p.start();
}

void start()
{
long [] a1 = {3,4,5};
33 15 15
long [] a2 = fixArray(a1);
System.out.print(a1[0] + a1[1] + a1[2] + " ");
System.out.println(a2[0] + a2[1] + a2[2]);
}

long [] fixArray(long [] a3)


{
a3[1] = 7;
return a3;
}
}
What will be the output of the program?
class TestClass
{
public static void main(String [] args)
{
TestClass p = new TestClass();
p.start();
}

void start()
{
34 String s1 = "hello"; hello world
String s2 = fixString(s1);
System.out.println(s1 + " " + s2);
}

String fixString(String s1)


{
s1 = s1 + "world";
System.out.print(s1 + " ");
return "world";
}
}

What will be output of the following code.


import java.util.Random;

public class OutputProg


{
35 public static void main(String [] args) output may be 125
{
Random rand=new Random();

for(int i=0;i<3;i++)
{
System.out.print(rand.ints(1,5,11).findFirst().getAsInt());
}
}
}
What will be output of following program
package javaq.java8.*;

import java.time.Clock;
36 Compilation Error
public class DateTimeTest
{
public static void main(String[] arg)
{
final Clock clock=Clock.systemUTC();
System.out.println(clock.instant());
System.out.println(clock.millis());
}
}

What is the output of the folllowing question. package


javaqs.question;

import java.time.Clock;
import java.time.ZoneId;
import java.time.ZonedDateTime;
37 public class ZonedDateTimeTest Compilation Error
{
public static void main(String arg[])
{
final Clock clock=Clock.systemUTC();
final ZonedDateTime zonedDatetime=ZonedDateTime.now();
final ZonedDateTime
zonedDatetimeFromClock=ZonedDateTime.now(clock);
final ZonedDateTime
zonedDatetimeFromZone=ZonedDateTime.now(ZoneId.of("America"));

System.out.println(zonedDatetime);
System.out.println(zonedDatetimeFromClock);
System.out.println(zonedDatetimeFromZone);
}
}
What will be the output of the following code.
package javaqs.question;

public class Calc


{
interface IntegerMath
38 { Compilation Error
int operation(int a,int b);
}
public int operateBinary(int a,int b,IntegerMath op);
{
return op.operation(a,b);
}
public static void main(String... args)
{
Calculator myApp=new Calculator();
IntegerMath addition=(a,b)->a+b;
IntegerMath substraction=(a,b)->a-b;
System.out.println("40 + 2="+myApp.operateBinary(40,2,addition));
System.out.println("20-
10="+myApp.operateBinary(20,10,substraction));
}
}

package javaqas.que;

public class Test


39 { Strings
public static void main(String [] args)
{
final String str="test";

str.chars().forEach(ch->System.out.println(ch));
}
}
package javaqs.que;

import java.util.Optional;

40 public class OptionalTest Full name :[none]


{
public static void main(String [] args)
{
Optional<String> fullname=Optional.of("Tom");
fullname=Optional.ofNullable(null);
System.out.println("Full name is set?"+fullname.isPresent());
System.out.println("Full Name:"+fullname.orElseGet(()->"[none]"));
System.out.println(fullname.map(s->"Hey"+s+"!").orElse("Hey
Stranger!"));
}
}

Consider the following code snippet:

public class WrapperClasses{


static void overloadedMethod(Number N){
System.out.println("Number Class Type");
}
41 static void overloadedMethod(Double D){ Number Class Type
System.out.println("Double Wrapper Class Type");
}

static void overloadedMethod(Long L){


System.out.println("Long Wrapper Class Type");
}

public static void main(String[] args){


int i = 21;

overloadedMethod(i);
}
}

Predict the correct output of the preceding code snippet.


Consider the following code snippet:

public class WrapperClasses{


static void overloadedMethod(Double D){
System.out.println("Double Wrapper Class Type");
}
42 Double Wrapper Class Type
static void overloadedMethod(Long L){
System.out.println("Long Wrapper Class Type");
}

public static void main(String[] args){


int i = 21;

overloadedMethod(i);
}
}

Predict the correct output of the preceding code snippet.


}

class SubClass extends SuperClass{


@Override
void methodOfSuperClass() throws IOException{
System.out.println("Sub class method");
}
}

class SubClassOne extends SuperClass{


@Override
void methodOfSuperClass() throws FileNotFoundException{
System.out.println("Sub class one method");
}
}

class SubClassTwo extends SuperClass{


@Override
void methodOfSuperClass() throws NullPointerException, Compile time error, can not
43 ArrayIndexOutOfBoundsException, FileNotFoundException{ be overrided with checked
System.out.println("Sub class two method"); exception with higher scope
}
}

class SubClassThree extends SuperClass{


@Override
void methodOfSuperClass() throws Exception{
System.out.println("Sub class three method");
}
}
class MainClass{
public static void main(String[] args){
SubClassThree s3=new SubClassThree();
s3.methodPfSuperClass();
}
}

Predict the correct output of the preceding code snippet.

Why final and abstract can not be used at a time? Select the correct
answer(s) from the following:
44 Only 1 and 2
1. “final” keyword is used to denote that a class or method does not
need further improvements.
2. “abstract” keyword is used to denote that a class or method needs
further improvements.
3. A final class or method can not be modified further where as
abstract class or method must be modified further.
Consider the following code snippet of Implementation of Comparator
interface using anonymous inner class:
45 Comparator<Student> idComparator = new Comparator<Student>() {
@Override
public int compare(Student s1, Student s2) {
return s1.getID()-s2.getID();
}
}; Comparator<Student>
idComparator = (Student s1,
Select the equivalent code of the above in java 8 using Lambda Student s2) => s1.getID()-
expression. s2.getID();

Consider the following code snippet:

46 Label label = new Label();


Button button = new Button("Send");
button.addActionListener((ActionEvent e) -> label.setText("Sent..."));

label = new Label();

Predict the correct output of the preceding code snippet. Compile time error
47

48 Select the benefits Of Lambda Expressions from the following:


1. Lambda expressions let you to write more clear, concise and flexible
code.
2. Lambda expressions removes verbosity and repetition of code. Only 1

Select the correct statements regarding Java ENUM from the following
list:
49
1. it is mandatory to declare enum constants with UPPERCASE letters.
2. Enum types like classes can have fields, constructors and methods
along with enum constants.
3. Enum constructors are public by default.
4. Enum constants are created only once for the whole execution. All
enum constants are created when you refer any enum constant first
time in your code. Only 1 and 2
Consider the following code snippet:

enum Enums
50 {
int i;

A, B, C;
} Compile time error, enum
constants must be declared
Predict the correct statement of the preceding code snippet. first.
Option2 Option3 Option4 Answer

reference, new reference, value new, value A

00001010 00000101 00010100 D

Statement A Statement B None of them A

switch(expression){
case Expr_1://statement(s) switch{
switch(expression){ break;
case Expr_2://statement(s) case Expr_1://statement(s)
case Expr_1://statement(s) break;
case Expr_2://statement(s) break; case Expr_2://statement(s)
. . break;
. . C
.
. .
case Expr_N://statement(s) case Expr_N://statement(s) ..
default://statement(s); break; case Expr_N://statement(s)
} default://statement(s); }
}

0
1 0
0 2 1
1 3 2
2 4 3
3 B
5 4
4 6 5
5 7 6
6 8 7
9
Calculating total number of Calculating total number of Calculating total number of A
rows elements indexes

After insertion = fruitsgood Compilation Error fruits are good A

A-II, B-III, C-IV, D-I A-IV, B-I, C-II, D-III A-III, B-IV, C-I, D-II C

29 31 15 15 30 30 D
The array variable, i, is used The array variable, j, is used to
The array variable, i, is used to to store the row data and the store the row data and the
store the row data and the variable, j, is used to store
variable, j, is used to store the i, is used to store the B
the column data of each jth variable,
column data of each ith row. column data of each ith row.
row.

abstract class GameConsole{ abstract class GameConsole{ abstract class GameConsole{


int score; int score;
int score;
public void displayScore(){ public void displayScore(){
System.out.println("Displaying public void displayScore(){
the computed score of played System.out.println("Displayin System.out.println("Displaying
game..."); the computed score of played
g the computed score of
abstract public void game...");
played game...");
computeScore(); abstract public void
abstract void
abstract public void computeScore();
computeScore();
playGame(); abstract public void
abstract void playGame(); playGame();
} }
class Badminton extends }
class Badminton extends
GameConsole{ class Badminton extends
GameConsole{
public override void GameConsole{
void playGame(){
playGame(){ System.out.println("Starting public void playGame(){
System.out.println("Starting System.out.println("Starting
the Badminton Game...");
the Badminton Game..."); the Badminton Game...");
}
} } D
void computeScore(){
public override void public void computeScore(){
computeScore(){
System.out.println("Computing System.out.println("Computi System.out.println("Computin
ng Badminton score... ");
Badminton score... "); g Badminton score... ");
}
} }
}
} }
class GameDemo{
class GameDemo{ class GameDemo{
public static void
public static void main(String[] main(String[] public static void
args){
args){ main(String[] args){
Badminton obj1=new
Badminton obj1=new Badminton obj1=new
Badminton();
Badminton(); Badminton();
obj1.playGame();
obj1.playGame(); obj1.playGame();
obj1.computeScore();
obj1.computeScore(); obj1.computeScore();
obj1.displayScore();
obj1.displayScore(); obj1.displayScore();
}
} }
}
} }

Race Condition Deadlock Condition Multithreading B


Statement B Both None of them B

Thread th = new Thread th = new Thread(); Thread th = new


Thread(MyThread); MyThread.run(); Thread(MyThread); th.start(); D

A-I, B-II, C-III, D-IV A-II, B-III, C-I, D-IV A-IV, B-III, C-II, D-I C
In main() method
i=0
,ThreadName=Thread-0
In main() method i=1
i=0 ,ThreadName=Thread-0 ,ThreadName=Thread-0
i=1 ,ThreadName=Thread-0 i=2
i=0 ,ThreadName=Thread-1 ,ThreadName=Thread-0 None C
i=2 ,ThreadName=Thread-0 i=0
i=1 ,ThreadName=Thread-1 ,ThreadName=Thread-1
i=2 ,ThreadName=Thread-1 i=1
end main() method ,ThreadName=Thread-1
i=2
,ThreadName=Thread-1
end main() method

0 1 None of the above B

if, switch if, break continue, if A

Compilation fails with an


0 error at line 8 due to
accessing non static member None of these C
in static method.
Exception is thrown at
Derived Compilation Error D
runtime

The program will compile


The program will lead to The program will lead to successfully and display 10 as B
compilation error. runtime error. output.

NumberEight NotEight Error A


The program has a compile The program runs in an
error because the adjustment is The program compiles and infinite loop because d<10 C
runs fine.
missing in the for loop. would always be true.

class ClassicJumble{
class ClassicJumble{
class ClassicJumble{ int choice=20;
int choice=20;
int choice=20; public void show(){
public void show(){
public void show(){ System.out.println(choice);
System.out.println(choice);
System.out.println(choice); }
}
} public void static
public void static D
public void static main(String[] main(String[] args){
main(String[] args){
args){ ClassicJumble obj1=new
ClassicJumble obj1;
obj1.show(); ClassicJumble();
obj1.show();
} obj1.show();
}
} }
} }

for(int i=0; i<10;){ for(int i=0; i<10;){ for(int i=0; i<10; i++){
System.out.println(++i); System.out.println(i); System.out.println(--i); B
} } }

An exception is thrown at
args[2] = 3 args[2] = null D
runtime.
static void add(int... args, int y){} static void add(int args...){} static void add(int...args){} D

1 - False, 2 - True, 3 - False, 4 - 1 - True, 2 - False, 3 - Ture, 4 1 - False, 2 - False, 3 - Ture, 4 - A


True - True False

Satement A is False, Statement Both are True Both are False A


B is True

1 2 3B
error at line 3 (static Compile error at line 4 (invalid
44 Compile argument type for method C
methods can't invoke this) main )

20 40 None of the above D


12 15 345375 375375 A
helloworld world world hello world helloworld hello world D

output may be 695 output may be 1511 output may be 456 2


Runtime Exception Compile and Execute without N
a one 3

Runtime Exception Compile and Execute without N


a one 2
Runtime Exception Compile and Execute without N
a one 3

Integers Characters Float 2


Runtime Exception Compile and Execute without Caompilation Error 1

Double Wrapper Class Type Long Wrapper Class Type Exception 1


Long Wrapper Class Type Compilation Error Exception 3
Compile the code but will
Sub class three method Exception 1
not execute

Only 1 and 3 Only 2 and 3 All are correct 4


Comparator<Student>
idComparator = (Student s1, Comparator<Student>
Student s2) -> s1.getID()- idComparator = (Student s1,
s2.getID(); Student s2) -> s1-s2; None of the above 2

Compile the code but will not Code will execute and show
execute predicted output Exception 1

Only 2 1 and 2 Neither 1 nor 2 3

Only 1 and 3 Only 2 and 3 Only 2 and 4 4


Compile the code but will not Code will execute and show
execute predicted output Exception 1
Concept Tested

Object Oriented
Programming
Using Java

Object Oriented
Programming
Using Java

Object Oriented
Programming
Using Java

Basic Programming Using Java

Basic Programming Using Java


Basic
Programming
Using Java

Basic
Programming
Using Java

Object Oriented
Programming
Using Java

Basic Programming Using Java


Basic
Programming
Using Java

Basic
Programming
Using Java

Working with Threads


Working with Threads

Working with Threads

Working with Threads


Working with Threads

Basic
Programming
Using Java

Basic
Programming
Using Java

Basic
Programming
Using Java
Basic
Programming
Using Java

Basic
Programming
Using Java

Basic
Programming
Using Java
Basic
Programming
Using Java

Object Oriented
Programming
Using Java

Basic Programming Using Java

Basic
Programming
Using Java
Basic
Programming
Using Java

Object Oriented
Programming
Using Java

Object Oriented
Programming
Using Java

Object Oriented
Programming
Using Java
Object Oriented
Programming
Using Java

Object Oriented
Programming
Using Java
Basic
Programming
Using Java
Basic
Programming
Using Java

Lambda and Predicate


Lambda and Predicate

Lambda and Predicate


Lambda and Predicate

Lambda and Predicate


Lambda and Predicate

Wrapper Classes
Wrapper Classes
Exception
handling

Object Oriented Programming Using Java


Lambda and Predicate

Lambda and Predicate

Lambda and Predicate

Java Datatype
Java Datatype
Q No Question

1 What do you mean by copy-constructor in Java? Explain with


example.

2 What is composition relationship in Java? Explain with example.


3 What are pass by reference and pass by value? Explain with
Example.
4 What is singleton class and how can we make a class singleton?

5 What is the difference between Enumeration and Iterator


interfaces?
6 What does System.gc() and Runtime.gc() methods do? Show the
implementation of both.
Write a code to check whether one string is a rotation of another.

[Hints:
s1 = "JavaJ2eeStrutsHibernate"
s2 = "StrutsHibernateJavaJ2ee"

Step 1 : Check whether s1 and s2 are of same length. If they are


7 not of same length then s2 is not rotated version of s1.
Step 2 : s3 = s1 + s1;

If s1 = “JavaJ2eeStrutsHibernate” then s3 =
“JavaJ2eeStrutsHibernateJavaJ2eeStrutsHibernate”.

Step 3 : Check whether s3 contains s2 using contains() method of


String class. If it contains then s2 is rotated version of s1.]
8 How do you count the number of occurrences of each character in
a string? Write a program by implemeting HashMap.
9 Write a java program to check whether two strings are anagram or
not.
Write a java program to reverse a given string with preserving the
position of spaces.
[Hints:
I Am Not String —> g ni rtS toNmAI
10
JAVA JSP ANDROID —> DIOR DNA PSJAVAJ
1 22 333 4444 55555 —> 5 55 554 4443 33221"
]
11 How To Read And Write Images In Java? Explain the process with
example.
12 Write a program to list all files in directory and its sub directories
recursively.
What are the different methods of Java 8 to iterate over a file
13 hierarchy and get list of all files and directory in it? Write a
program to list all files and directories using any one them.
14 Can a static nested class contain both static and non-static
members? Write a program by implementing static nested class.
15 Can a method contain any number of synchronized blocks? Explain
with example.
Answer

Java does support copy constructors like C++, but the difference lies in the fact that Java does not create a
default copy constructor if you do not write your own.

Copy constructor for Car class is shown below:

public class Car extends Vehicle


{
private String carName;
public Car(String carName)
{
this.carName = carName;
}
public Car(Car c)
{
this.carName = c.carName;
}
}

Composition is exactly like Aggregation except that the lifetime of the ‘part’ is controlled by the ‘whole’. This
control may be direct or transitive. That is, the ‘whole’ may take direct responsibility for creating or destroying
the ‘part’, or it may accept an already created part, and later pass it on to some other whole that assumes
responsibility for it.

Sample class Car is shown below to demonstrate Composition of tires, doors, windows and steering.

public class Car


{
private Tire[] tires;
private Door[] doors;
private Steering steering;
private Window[] windows;
}
class Tire
{

}
class Door
{

}
class Steering
{

}
class Window
{

}
that the actual object is not passed, rather a reference of the object is passed. Thus, any changes made by the
external method, are also reflected in all places.

Sample code is presented below which shows pass by value.

Pass by Value:
public class ComputingEngine
{
public static void main(String[] args){
int x = 15;
ComputingEngine engine = new ComputingEngine();
engine.modify(x);
System.out.println("The value of x after passing by value "+x);
}
public void modify(int x){
x = 12;
}
}
Below example shows pass by reference in the code.

Pass by Reference:
public class ComputingEngine{
public static void main(String[] args){
ComputingEngine engine = new ComputingEngine();
Computation computation = new Computation(65);
engine.changeComputedValue(computation);
System.out.println("The value of x after passing by reference "+ computation.x);
}

public void changeComputedValue(Computation computation){


computation = new Computation();
computation.x = 40;
}
}

class Computation{
int x;
Computation(int i) { x = i; }
In a singleton class we:
i. ensure that only one instance of the singleton class ever exists
ii. provide global access to that instance

To create a singleton class we:


i. declare all constructors of the class as private
ii. provide a static method that returns a reference to the instance

Sample code below shows Double checked Singleton class implementation.


public class DoubleCheckedSingleton {
private static volatile DoubleCheckedSingleton instance;
public static DoubleCheckedSingleton getInstance() {
if (instance == null) {
synchronized (DoubleCheckedSingleton .class) {
if (instance == null) {
instance = new DoubleCheckedSingleton();
}
}
}
return instance;
}
}

Enumeration is twice as fast as compared to an Iterator and uses very less memory. However, the Iterator is
much safer compared to Enumeration, because other threads are not able to modify the collection object that
is currently traversed by the iterator. Also, Iterators allow the caller to remove elements from the underlying
collection, something which is not possible with Enumerations.
These methods can be used as a hint to the JVM, in order to start a garbage collection. However, this it is up to
the Java Virtual Machine (JVM) to start the garbage collection immediately or later in time.

Sample class ReferenceObject is shown below to demonstrate the usage of System.gc and Runtime.gc
methods.

public class ReferenceObject{


public void finalize() {
System.out.println("object is garbage collected");
}

public static void main(String args[]){


ReferenceObject refObj1=new ReferenceObject();
ReferenceObject refObj2=new ReferenceObject();
refObj1=null;
refObj2=null;
System.gc();

Runtime.gc();
}
}
public class MainClass{
public static void main(String[] args){
String s1 = "JavaJ2eeStrutsHibernate";

String s2 = "StrutsHibernateJavaJ2ee";

//Step 1

if(s1.length() != s2.length()){
System.out.println("s2 is not rotated version of s1");
}
else{
//Step 2

String s3 = s1 + s1;

//Step 3

if(s3.contains(s2)){
System.out.println("s2 is a rotated version of s1");
}
else{
System.out.println("s2 is not rotated version of s1");
}
}
}
}
private static void characterCount(String inputString){
//Creating a HashMap containing char as a key and occurrences as a value

HashMap<Character, Integer> charCountMap = new HashMap<Character, Integer>();

//Converting given string to char array

char[] strArray = inputString.toCharArray();

//checking each char of strArray


for (char c : strArray){
if(charCountMap.containsKey(c)){
//If char 'c' is present in charCountMap, incrementing it's count by 1

charCountMap.put(c, charCountMap.get(c)+1);
}
else{
//If char 'c' is not present in charCountMap,
//putting 'c' into charCountMap with 1 as it's value

charCountMap.put(c, 1);
}
}

//Printing inputString and charCountMap

System.out.println(inputString+" : "+charCountMap);
}

public static void main(String[] args){


characterCount("Java J2EE Java JSP J2EE");

characterCount("All Is Well");

characterCount("Done And Gone");


}
}
Arrays.sort(s2Array);

//Checking whether s1Array and s2Array are equal

status = Arrays.equals(s1Array, s2Array);


}

//Output

if(status){
System.out.println(s1+" and "+s2+" are anagrams");
}
else{
System.out.println(s1+" and "+s2+" are not anagrams");
}
}

public static void main(String[] args){


isAnagram("Mother In Law", "Hitler Woman");

isAnagram("keEp", "peeK");

isAnagram("SiLeNt CAT", "LisTen AcT");

isAnagram("Debit Card", "Bad Credit");

isAnagram("School MASTER", "The ClassROOM");

isAnagram("DORMITORY", "Dirty Room");

isAnagram("ASTRONOMERS", "NO MORE STARS");

isAnagram("Toss", "Shot");

isAnagram("joy", "enjoy");
}
}
if (inputStringArray[i] == ' '){
resultArray[i] = ' ';
}
}

//Initializing 'j' with length of resultArray

int j = resultArray.length-1;

//Second for loop :


//we copy every non-space character of inputStringArray
//from first to last at 'j' position of resultArray

for (int i = 0; i < inputStringArray.length; i++){


if (inputStringArray[i] != ' '){
//If resultArray already has space at index j then decrementing 'j'

if(resultArray[j] == ' '){


j--;
}

resultArray[j] = inputStringArray[i];

j--;
}
}

System.out.println(inputString+" ---> "+String.valueOf(resultArray));


}

public static void main(String[] args){


reverseString("I Am Not String");

reverseString("JAVA JSP ANDROID");

reverseString("1 22 333 4444 55555");


}
}
File file = new File(“Pass the image file location here”)

URL url = new URL(“Pass the URL of image file here”)

Step 2 : Read the image using ImageIO.read() method into BufferedImage object.

BufferedImage image = ImageIO.read(file or url)

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;

public class ReadAndWriteImage{


public static void main(String[] args){
File file = new File("I:/input.jpg");

BufferedImage image = null;

try{
image = ImageIO.read(file);

ImageIO.write(image, "jpg", new File("I:/output.jpg"));

ImageIO.write(image, "png", new File("I:/output.png"));

ImageIO.write(image, "gif", new File("I:/output.gif"));

ImageIO.write(image, "bmp", new File("I:/output.bmp"));


}
catch (IOException e){
e.printStackTrace();
}

System.out.println("done");
}
}
import java.io.File;

public class MainClass{


private static void listFiles(String path){
File folder = new File(path);

File[] files = folder.listFiles();

for (File file : files){


if (file.isFile()){
System.out.println(file.getName());
}
else if (file.isDirectory()){
listFiles(file.getAbsolutePath());
}
}
}

public static void main(String[] args){


listFiles("F:/Path");
}
}
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Stream;

public class Java8ListFilesInDirectory


{
public static void main(String[] args) throws IOException
{
Stream<Path> files = Files.list(Paths.get("F:\\Games"));
files.forEach(System.out::println);

files.close();
}
}

OR

Files.walk() Java 8 Method Example : List All Files And Directories

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Stream;

public class Java8ListFilesInDirectory


{
public static void main(String[] args) throws IOException
{
Stream<Path> files = Files.walk(Paths.get("F:\\Games"));

files.forEach(System.out::println);

files.close();
}
}
Yes, static nested classes can contain both static and non-static members.

class OuterClass{
//Some members of OuterClass

static class NestedClass{


static int i; //Static Field

int j; //Non-static Field

void methodOne(){
//Non-static method
}

static void methodTwo(){


//Static Method
}
}
}
Yes, a method can contain any number of synchronized blocks. This is like synchronizing multiple parts of a
method.

class Shared
{
static void staticMethod()
{
synchronized (Shared.class)
{
//static synchronized block - 1
}

synchronized (Shared.class)
{
//static synchronized block - 2
}
}

void NonStaticMethod()
{
synchronized (this)
{
//Non-static Synchronized block - 1
}

synchronized (this)
{
//Non-static Synchronized block - 2
}
}
}
Concept Tested

Object Oriented programming

Object Oriented programming


Java Basic
Object Oriented programming

Java Collection
Java Basic
Java Collection
Java Collection
Java Collection
Java Collection
Java IO and NIO
Java IO and NIO
Java IO and NIO
Nested Class
Nested Class

Você também pode gostar