0% found this document useful (0 votes)
4 views29 pages

java all test

The document contains a series of Java programming questions and code snippets related to static and non-static variables, encapsulation, inheritance, and typecasting. Each section presents a code snippet followed by multiple-choice options for the expected output. The document also includes explanations for the correct answers to the questions.

Uploaded by

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

java all test

The document contains a series of Java programming questions and code snippets related to static and non-static variables, encapsulation, inheritance, and typecasting. Each section presents a code snippet followed by multiple-choice options for the expected output. The document also includes explanations for the correct answers to the questions.

Uploaded by

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

//static

1]What will be the output of the following code snippet?


class Demo {
static int x = 5;
static int y;
static {
y = x * 2;
x = y - 3;
}
public static void main(String[] args) {
System.out.println(x + " " + y);
}
}
// Options:
// A) 5 10
// B) 7 10
// C) 10 7
// D) 7 7

2]// Question 8: Static Variables


// What will be the output of the following code snippet?
class Counter {
static int count = 0;
Counter() {
count++;
}
public static void main(String[] args) {
new Counter();
new Counter();
System.out.println(count);
}
}
// Options:
// A) 0
// B) 1
// C) 2
// D) Compilation Error

3]
public class Demo {
static int a = test();

static int test() {


int a = 10;
System.out.println(Demo.a);
return a;
}

public static void main(String[] args)


{
System.out.println("main started");
System.out.println(a);
System.out.println("main ended");
}
}

What will be the output of the following code snippet?


class StaticTest {
static int counter = 0;
StaticTest()
{
counter++;
}
static void printCounter()
{
System.out.println("Counter: " + counter);
}
public static void main(String[] args) {
new StaticTest();
new StaticTest();
StaticTest.printCounter();
}
}
// Options:
// A) Counter: 0
// B) Counter: 1
// C) Counter: 2
// D) Compilation Error

//non static
4]What will be the output of the following code snippet?
class Demo {
int a = 3;
int b = 4;
void m1() {
int temp = a;
a = b;
b = temp;
}
public static void main(String[] args) {
Demo obj = new Demo();
obj.m1();
System.out.println(obj.b + ", " + obj.a);
}
}
// Options:
// A) 4, 3
// B) 3, 4
// C) 0, 0
// D) Compilation Error

5]
public class Demo2
{
int x=10;
static int y=20;

{
x=y++;
}
public static void main(String[] args)
{
System.out.println("main started");
System.out.println(x);
System.out.println("main ended");
}
}

6]
public class Demo2
{
int x=10;
static int y=20;
{
y=x++;
}
public static void main(String[] args)
{
System.out.println("main started");
System.out.println(y);
System.out.println("main ended");
}
}
o/p:
main started
20
main ended

6 done

packages and modifiers

7]
package p2;
class Demo1
{
public String name;
}

package p1;
import p2.Demo1;//CTE
public class Demo2
{
public static void main(String[] args)
{
Demo1 d1=new Demo1();
d1.name="myname";
System.out.println(d1.name);
}
}
o/p
A]myname
B]null
c]CTE
D]CTE in object creation line

8]
package p2;
public class Demo1
{
Demo1()
{
System.out.println("Demo1 object created");
}
}

package p1;
import p2.Demo1;
public class Demo2
{
public static void main(String[] args)
{
Demo1 d1=new Demo1();
}
}

9]
package p2;
public class Demo1
{
public int x;
public Demo1()
{
System.out.println("Demo1 object created");
}
protected Demo1(int x)
{
this();
this.x=x;
}
}
package p1;
import p2.Demo1;
public class Demo2
{
public static void main(String[] args)
{
Demo1 d1=new Demo1();
System.out.println(d1.x);
}
}

o/p
===
Demo1 object created
0

10]

package p2;
public class Demo1
{
public int x;
public Demo1()
{
System.out.println("constructor one");
}
public Demo1(int x)
{
this();
System.out.println("constructor two");
this.x=x;
}
}

package p1;
import p2.Demo1;
public class Demo2
{
public static void main(String[] args)
{
Demo1 d1=new Demo1(25);
System.out.println(d1.x);
}
}

Question :
A local weather station has recorded the daily high temperatures
for a week. These temperatures are: 30 32 28 35 31 33 29.
The station wants to know if there was any day where the
temperature was significantly hotter than the previous day.
Specifically, they consider a day "significantly hotter"
if its temperature is at least 5 degrees Celsius higher
than the temperature of the day before it.
Can you help them determine if such a day occurred in the
recorded week?
Question Description :
create an array of size 7 to store weekly temperature.
Write a Java function that takes an array of daily temperatures and returns true if
there was a significantly hotter day, and false otherwise.
Use scanner class and initialize the array.

sol:
import java.util.Scanner;
class Main{

public static boolean hasSignificantlyHotterDay(int[] temperatures) {


for (int i = 1; i < temperatures.length; i++) {
if (temperatures[i] >= temperatures[i - 1] + 5) {
return true;
}
}
return false;
}
public static void main(String []args){
Scanner scanner = new Scanner(System.in);
int[] dailyTemperatures = new int[7];
for (int i = 0; i < 7; i++) {
dailyTemperatures[i] = scanner.nextInt();
}
System.out.println(hasSignificantlyHotterDay(dailyTemperatures));
}
}

====================================================
ENCAPSULATOIN
===================================================================================
===================
1]
public class Account
{

private double balance = 100;


public double getBalance() {
return balance;
}

public void deposit(double amount)


{
if(amount>0)
balance += amount;
}
public static void main(String[] args) {
Account acc = new Account();
acc.deposit(50);
System.out.println(acc.getBalance());
}
}

A) 100
B) 50
C) 150 [correct]
D) 100

2]
package test2;
public class BankAcc
{
private int pin=1234;

private int bal=1200;

public void withdraw(int amount,int pin) {


if(this.bal>amount &&this.pin==pin)
this.bal-= amount;
else
System.out.println("invalid pin");
}
}

public class Main


{
public static void main(String[] args)
{
BankAcc b=new BankAcc();
b.withdraw(500, 1234);
System.out.println(b.bal);
}
}
A) 700
B) CTE [correct]
C) 1200
D) invalid pin

3]
public class Student
{
private long phoneno;
public Student()
{
setPhoneno(7356481687l);
}

public long getPhoneno() {


return phoneno;
}
}

public class Main


{
public static void main(String[] args)
{
Student s=new Student();
System.out.println(s.getPhoneno());
}
}
A) CTE [correct]
B) 7356481687
C) 0
D) Runtime Error

===================================================================================
=====================

PLAYING WITH OBJECTS


===================================================================================
=====================

4]
class Base {

}
class Child extends Base {

public class Test {


void show(Base b) {
System.out.println("Base");
}
void show(Child c) {
System.out.println("Child");
}

public static void main(String[] args) {


Test t = new Test();
Base b = new Child();
t.show(b);
}
}

A) Child
B) Base
C) Compilation error
D) Runtime error

Answer: B) Base

Method overloading is resolved at compile-time, based on reference type.


Though object is Child, reference is Base, so show(Base) is called.
No runtime polymorphism for overloading.

5]
public class A
{
int x=10;
public static void m1(B b)
{
System.out.println(b.y);
}
}

public class B
{
int y=20;

public static void m1(A a)


{
System.out.println(a.x);
}

public static void main(String[] args)


{
A.m1(new B());
}
}

A) 10
B) no output
C) Compilation error
D) 20 [correct]

6]
public class A
{
int x=10;
public static B createB()
{
return new B();
}
}

public class B
{
int y=20;
public static void main(String[] args)
{
B b=A.createB();
System.out.println(b.y);
}
}

A) 10
B) 20 [correct]
C) Compilation error
D) no output

===================================================================================
=====================

HAS-A
===================================================================================
=====================

7]
class Engine {
private String type = "V8";
public String getType( ) {
return type;
}
}

class Car {
private Engine engine = new Engine( );
public Engine getEngine( ) {
return engine;
}
}

public class Test {


public static void main(String[ ] args) {
Car car = new Car( );
System.out.println(car.getEngine( ).getType( ));
}
}

A) null
B) Compilation error
C) V8
D) Runtime exception

Answer: C) V8

Encapsulation is respected using private with a proper getter.


The Car has-a Engine object.
Calling getType() returns the engine type.
8]
class Engine {
String type = "Diesel";
}

class Truck {
private Engine engine = new Engine( );

public Engine getEngine( ) {


return engine;
}
}

public class Test {


public static void main(String[ ] args) {
Truck t = new Truck( );
t.getEngine( ).type = "Electric";
System.out.println(t.getEngine( ).type);
}
}

A) Diesel
B) Electric
C) null
D) Compilation error

Answer: B) Electric

Even though engine is private, getter leaks its reference.


We modify the internal type via reference.
Encapsulation is broken indirectly.

9]
class Address {
String city = "Chennai";
}

class Person {
private Address addr = new Address( );
Address getAddress( ) {
return addr;
}
}

public class Test {


public static void main(String[ ] args) {
Person p = new Person( );
p.getAddress( ).city = "Mumbai";
System.out.println(p.getAddress( ).city);
}
}

A) Hyderabad
B) Mumbai
C) Compilation error
D) null

Answer: B) Mumbai
getAddress() returns the reference to internal object.
You directly update city through that.
Again, this breaks encapsulation.

===================================================================================
=====================

IS-A
===================================================================================
=======================
10]
class A {
static {
System.out.println("Static A");
}

{
System.out.println("Instance A");
}

A( ) {
System.out.println("Constructor A");
}
}

class B extends A {
static {
System.out.println("Static B");
}

{
System.out.println("Instance B");
}

B( ) {
System.out.println("Constructor B");
}
}
public class Test {
public static void main(String[ ] args) {
B obj = new B( );
}
}

A) Static B → Static A → Instance A → Constructor A → Instance B → Constructor B


B) Static A → Static B → Instance A → Constructor A → Instance B → Constructor B
C) Static B → Static A → Constructor A → Constructor B
D) Static A → Static B → Constructor B

Answer: B) Static A → Static B → Instance A → Constructor A → Instance B →


Constructor B

Static blocks run top-down during class loading.


Then, instance blocks and constructors execute from superclass to subclass.
That’s why A's blocks and constructor execute before B's.

11]
public class Parent {

static int i = 1000;

public Parent(int i) {
this.i = i;
}

static {
Parent parent = new Child();
parent.m1();
}

public void m1() {


System.out.println(i);
}

public static void main(String[] args) {


Parent parent = new Parent(10);
parent.m1();
}
}

-----------------------------------------------------------------------------------
-------
public class Child extends Parent {

A) Compile Time Error

B) 1000 ( correct option )


10

C) ClassCastException

D) 10
1000

12]

class Parent {
int x = getX( );

public Parent( ) {
System.out.println("Parent Constructor: " + x);
}

public int getX( ) {


return 100;
}
}
class Child extends Parent {
int x = 200;

public Child( ) {
System.out.println("Child Constructor: " + super.x);
}

public static void main(String[ ] args) {


Parent p = new Child( );
}
}

✅A) Parent Constructor: 100


Child Constructor: 0

B) Parent Constructor: 100


Child Constructor: 100

C) Parent Constructor: 0
Child Constructor: 100

D) Parent Constructor: 0
Child Constructor: 0

Explanation: When new Child( ) is called, Java first calls the Parent constructor
due to constructor chaining. Before the Parent constructor runs, instance variables
are initialized, so Parent's x is set by calling getX( ), which returns 100.
Therefore, the first print statement in the Parent constructor outputs Parent
Constructor: 100. After that, the Child constructor runs, and it prints Child
Constructor: " + super.x. Here’s the tricky part: although Child also defines its
own x = 200, it shadows the parent’s x. However, super.x refers specifically to the
Parent's version of x, and at the time it’s accessed in the Child constructor, it's
not yet properly constructed in the context of Child, so it results in the default
value of 0 due to how memory is laid out and initialized. This leads to the second
line of output being Child Constructor: 0.

===================================================================================
==============================

N P-TYPECASTING
===================================================================================
=====================
13]
class Vehicle {

class Bike extends Vehicle {


void ride( ) {
System.out.println("Bike ride");
}
}

class Car extends Vehicle {


void drive( ) {
System.out.println("Car drive");
}
}
public class Test {
public static void main(String[ ] args) {
Vehicle v = new Car( );
((Bike)v).ride( );
}
}

A) Bike ride
B) Car drive
C) Compilation error
D) Runtime ClassCastException

Answer: D) Runtime ClassCastException

v is a Car object, not a Bike.


Downcasting to unrelated type throws ClassCastException.
Compile-time is fine, but runtime fails.

14]
class X {

}
class Y extends X {

}
class Z extends X {

public class Test {


public static void main(String[ ] args) {
X obj = new Z( );
Y y = (Y) obj;
System.out.println("Done");
}
}

A) Prints “Done”
B) Compile-time error
C) ClassCastException at runtime
D) No output, program ends normally

Answer: C) ClassCastException at runtime

You can’t cast a Z object to Y — they’re sibling classes.


Compiler allows it, but JVM throws exception.
So it crashes at runtime.

15]

public class Parent


{

public class Child extends Parent


{
public void m1()
{
System.out.println("child m1");
}
public static void main(String[] args)
{
Parent p=new Child();
p.m1();
}
}

A) child m1
B) Compile-time error
C) ClassCastException at runtime
D) No output, program ends normally

programming:
======
Q3. Given an integer array Arr of size N. The task is to find the count of elements
whose value is greater than all of its prior elements.
Note: 1st element of the array should be considered in the count of the result. For
example, Arr[]={7,4,8,2,9) As 7 is the first element, it will consider in the
result. 8 and 9 are also the elements that are greater than all of its previous
elements. Since total of 3 elements is present in the array that meets the
condition.
Hence the output = 3.
Example 1:
Input 5 -> Value of N, represents size of Arr
7-> Value of Arr[0]
4 -> Value of Arr[1]
8-> Value of Arr[2]
2-> Value of Arr[3]
9-> Value of Arr[4]
Output : 3

class GreaterThanLast {

public static int countGreater(int [] arr){


int count=1;
for(int i=1;i<arr.length;i++){
if(arr[i]>arr[i-1]){
count++;
}
}
return count;
}

public static void main(String[] args) {


Scanner sc=new Scanner(System.in);
int size=sc.nextInt();
int [] arr= new int[size];
for(int i=0;i<arr.length;i++){
arr[i]=sc.nextInt();
}
int res= countGreater(arr);
System.out.println(res);
}
}

=============================
Question :
Write a complete Java program that takes an array of integers from the user and
calculates the average of the second half even indexed element of the array
elements.
You are required to write a Java program that:
1. Accepts input from the user to create an integer array.
2. Ensures the array has an even number of elements.
3. Calculates the average of the second half even indexed of the array.
4. Displays the average as a double.

public static double averageSecondHalf(int[] arr)

Test Case 1 :
Inputs : 8 2 4 6 8 10 12 14 16
Output :
12.0

Test Case 2 :
Inputs : 4 , -10 , -20 , -30 , -40
Output :
-30.0

Test Case 2 :
Inputs : 6 , 0 , 0 , 0 , 0 , 0 , 0
Output :
0.0

Test Case 3 :
Inputs : 2 , 5 , 15
Output :

SOLN:
import java.util.Scanner;
class Main{

public static void main(String []args){

Scanner scanner = new Scanner(System.in);

// Step 1: Read the size of the array


int n = scanner.nextInt();

// Step 2: Check if the number is even


if (n % 2 != 0) {
return;
}

// Step 3: Create array and take input


int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = scanner.nextInt();
}

// Step 4: Calculate and print the average of the second half


double average = averageSecondHalf(arr);
System.out.print(average);

public static double averageSecondHalf(int[] arr) {


int sum = 0;
int count=0;
int half = arr.length / 2;

for (int i = half; i < arr.length; i++) {


if(i%2==0){
sum += arr[i];
count++;
}
}

return (double) sum / count;


}
}

===============================

1.
class Account {
private int balance = 1000;

public void deposit(int amount) {


balance += amount;
}

public int getBalance() {


return balance;
}

public static void main(String[] args) {


Account a = new Account();
a.deposit(500);
System.out.println(a.getBalance());
}
}

**What is the output?**


A. 500
B. 1000
C. 1500
D. Compilation Error

✅ **Answer: C. 1500**
===================================================================================
==========================================

2.class Account {
private int balance = 1000;
public void deposit(int amount) {
if (amount > 0) {
balance += amount;
}
}

public int getBalance() {


return balance;
}

public static void main(String[] args) {


Account a = new Account();
a.deposit(-200);
a.deposit(700);
System.out.println(a.getBalance());
}
}

What is the output?

A. 800
B. 1000
C. 1700
D. 1700

✅ Answer: C. 1700

===================================================================================
=================================
Copying the Object Reference (3 Questions)

3.
class Counter {
int count = 0;
}

public class Main {


public static void main(String[] args) {
Counter c1 = new Counter();
c1.count = 5;
Counter c2 = c1;
c2.count++;
System.out.println(c1.count);
}
}

**What is the output?**


A. 5
B. 6
C. Compilation Error
D. 0

✅ **Answer: B. 6

===================================================================================
=============================================
4.
class Pen {
String color;
}

public class Main {


public static void main(String[] args) {
Pen p1 = new Pen();
p1.color = "Blue";
Pen p2 = p1;
p2.color = "Black";
System.out.println(p1.color);
}
}

**What is the output?**


A. Blue
B. Black
C. null
D. Compilation Error

5.
class Engine {
String status = "OFF";
}

class Mechanic {
static void startEngine(Engine e) {
e.status = "ON";
}
}

public class Main {


public static void main(String[] args) {
Engine eng = new Engine();
Mechanic.startEngine(eng);
System.out.println(eng.status);
}
}

a) OFF
b) ON ✅
c) null
d) Compilation Error
===================================================================================
=================================
6.
class A {
void show()
{
System.out.println("Class A");
}
}

class B extends A {
void show()
{
System.out.println("Class B");
}
}

class C extends B {}

public class Main {


public static void main(String[] args) {
C obj = new C();
obj.show();
}
}

a) Class A
b) Class B ✅
c) Compilation error
d) Runtime error

7.
class Animal
{
void sound()
{
System.out.println("Animal sound");
}
}

class Dog extends Animal {


void bark()
{
System.out.println("Dog barks");
}
}

class Cat extends Animal {}

public class Main {


public static void main(String[] args) {
Animal a = new Cat();
Dog d = (Dog) a;
d.bark();
}
}

a) Dog barks
b) Animal sound
c) ClassCastException at runtime ✅
d) Compilation error
===================================================================================
===
8. class Animal {
String type;

Animal getAnimal() {
Animal a = new Animal();
a.type = "Mammal";
return a;
}
public static void main(String[] args) {
Animal a = new Animal();
Animal b = a.getAnimal();
System.out.println(b.type);
}
}

Output?

A. null
B. Mammal
C. Compilation Error
D. Runtime Error

✅ Answer: B. Mammal
===================================================================================
====================
9. Inheritance Hierarchy

class A {}
class B extends A {}
class C extends B {}

public class Main {


public static void main(String[] args) {
C obj = new C();
System.out.println(obj instanceof A);
}
}
Output?

A. true
B. false
C. Compilation Error
D. Runtime Error

✅ Answer: A. true

===================================================================================
=================
10.
class Parent {
Parent() {
System.out.println("Parent");
}
}

class Child extends Parent {


Child() {
System.out.println("Child");
}

public static void main(String[] args) {


new Child();
}
}
Output?
A. Parent
B. Child
C. Parent Child
D. Child Parent

✅ Answer: C. Parent Child

===================================================================================
====================
11.

class A {
int i = 10;
}

public class Main {


public static void main(String[] args) {
A a1 = new A();
A a2 = new A();
System.out.println(a1 == a2);
}
}
Output?

A. true
B. false
C. Compilation Error
D. 10

✅ Answer: B. false
===================================================================================
======================
12.class Book {
String title;

Book(String t) {
title = t;
}
}

class Library {
Book book = new Book("Java Basics");
}

public class Main {


public static void main(String[] args) {
Library lib = new Library();
System.out.println(lib.book.title);
}
}

What is the output?

A. null
B. Java Basics
C. Book
D. Compilation Error

✅ Answer: B. Java Basics


===================================================================================
=========================

13.class Wheel {
int size = 16;
}

class Bike {
Wheel frontWheel = new Wheel();
Wheel backWheel = new Wheel();
}

public class Main {


public static void main(String[] args) {
Bike b = new Bike();
System.out.println(b.frontWheel.size + b.backWheel.size);
}
}

What is the output?

A. 16
B. 32
C. 0
D. Compilation Error

✅ Answer: B. 32
===================================================================================
===============================

14.
class Address {
String city = "New York";
}

class Person {
Address address;
}

public class Main {


public static void main(String[] args) {
Person p = new Person();
System.out.println(p.address);
}
}

What is the output?

A. New York
B. null
C. address
D. Compilation Error

✅ Answer: B. null
===================================================================================
===================================
15.
class Mouse {
String brand = "Logitech";
}

class Desktop {
Mouse getMouse() {
return new Mouse();
}
}

public class Main {


public static void main(String[] args) {
Desktop d = new Desktop();
System.out.println(d.getMouse().brand);
}
}
What is the output?

A. Logitech
B. HP
C. null
D. Compilation Error

✅ Answer: A. Logitech
===================================================================================
===================================
Programming Question:

A logistics company tracks the delivery times (in days) of packages. Given an
integer array deliveryDays,
return the number of packages that were delivered faster than the average delivery
time.
A package is considered faster if its delivery time is strictly less than the
average of all delivery times.

Input: deliveryDays = [3, 5, 2, 6, 4, 3]


Output: 3

Explanation:
Average delivery time = (3+5+2+6+4+3) / 6 = 23 / 6 ≈ 3.83
Faster deliveries = [3, 2, 3] → Count = 3

Input: deliveryDays = [7, 7, 7, 7]


Output: 0

Explanation:
Average = 7.0 → No delivery is strictly less than average

Input: deliveryDays = [1, 2, 3]


Output: 1

Explanation:
Average = (1+2+3)/3 = 2.0 → Only 1 is strictly less than 2

Solution:

public class Solution {


public int countFasterDeliveries(int[] deliveryDays) {
int sum = 0;
for (int day : deliveryDays) {
sum += day;
}
double average = (double) sum / deliveryDays.length;

int count = 0;
for (int day : deliveryDays) {
if (day < average) {
count++;
}
}
return count;
}
}

============================
❓ Problem: Overlapping Pairwise Non-Negative Difference Sort

You are given an integer array nums of length n. Your task is to iterate over
overlapping pairs of the array, i.e., (nums[0], nums[1]), (nums[1],
nums[2]), (nums[2], nums[3]), ..., (nums[n - 2], nums[n - 1]).

For each pair (nums[i], nums[i + 1]):

If the difference nums[i] - nums[i + 1] is negative, swap the elements at indices i


and i + 1.

Return the modified array after processing all overlapping pairs in one left-to-
right pass.

🔁 Rules:

You must compare consecutive overlapping pairs.

Only one pass over the array is allowed (left to right).

Each swap affects subsequent pairs (i.e., it's not all comparisons first, then all
swaps — you swap and continue).
🖼 Example 1:
Input:
nums = [4, 2, 5, 7]
Output:
[4, 5, 7, 2]
Explanation:
Pair (4, 2): 4 - 2 = 2 → no swap
Pair (2, 5): 2 - 5 = -3 → swap → [4, 5, 2, 7]
Pair (2, 7): 2 - 7 = -5 → swap → [4, 5, 7, 2]
🖼 Example 2:
Input:
nums = [3, 1, 4]
Output:
[3, 4, 1]
Explanation:
Pair (3, 1): 3 - 1 = 2 → no swap
Pair (1, 4): 1 - 4 = -3 → swap → [3, 4, 1]
💡 Constraints:
1 <= nums.length <= 10^4
-10^4 <= nums[i] <= 10^4

Method Signature:

public int[] overlappingPairwiseNonNegative(int[] nums)

SOLN:
====
import java.util.Scanner;
class Main {
public static void main(String []args){
Scanner s= new Scanner(System.in);
int size=s.nextInt();

int[] arr=new int[size];


for(int i=0;i<arr.length;i++){
arr[i]=s.nextInt();
}

arr= overlappingPairwiseNonNegative(arr);
for(int i=0;i<arr.length;i++){
System.out.println(arr[i]);
}

}
public static int[] overlappingPairwiseNonNegative(int[] nums) {
for (int i = 0; i < nums.length - 1; i++) {
if (nums[i] - nums[i + 1] < 0) {
// Swap if the difference is negative
int temp = nums[i];
nums[i] = nums[i + 1];
nums[i + 1] = temp;
}
}
return nums;
}
}
====================================
1.what is the output of the following code.

import java.util.Arrays;
package sample;

public class Demo {

public static void main(String[] args) {


System.out.println("Hello world");
}
}

No output
Hello world
run time error
compile time error

2. When the non-static initializers will be executed?

during class loading


during object loading
during compilation
when we call the non-static initializer

3.what is the output of the following code.


class Test {
static int x = 10;

static {
x += 5;
}
public static void main(String[] args) {
System.out.println(x);
}
static {
x *= 2;
}
}
A. 10
B. 15
C. 30
D. Compilation Error

4.What is the scope of the default constructor

public scope
default scope
same as class scope
protected scope

5.Which of the following is TRUE about non-static initializer blocks in Java?


A. They are executed after constructors
B. They are executed only once when class is loaded
C. They run every time an object is created, before the constructor
D. They must be declared public

6.what is the output of the following code.


package sample;
public class Demo {

static int a = demo();

static int demo()


{
return 10;
}
public static void main(String[] args) {
System.out.println(a);
}
}

0
compile time error
10
run time error

7.Which of the following is the correct execution order when an object is created?
A. Static block → Constructor → Instance block
B. Instance block → Static block → Constructor
C. Static block → Instance block → Constructor
D. Constructor → Instance block → Static block

8.What happens if a outer class is declared protected?


A. It's accessible everywhere
B. It’s accessible only in the same package
C. Compilation error
D. Accessible to subclasses in any package

9.Which of the following statements is TRUE about non-static variables?


A. They are shared across instances
B. They can only be accessed from static methods
C. Each object has its own copy
D. They are initialized at class loading

10.what is the output of the following code.


package sample;
public class Demo {
//static initializer
private static
{
System.out.println("staic");
}

public static void main(String[] args) {


System.out.println("main");
}
}

main

main
static

static
main
compile time error

Program:
You are working as a data analyst for an e-commerce platform. The company collects
customer orders, but due to system glitches, some orders get duplicated in the
database.
Your task is to count only the unique Id's from all the order IDs.

Note : All the order id's are stored in the form of array

Example:-

size=5
arr=[101,102,102,103,102]
output: 2 (101 and 103 are unique)
Note:
i) Read the size
ii) Read the array elements
Note: assume Integer.MIN_VALUE is not present in the array

SOLN:
class Main {
public static void main(String[] args) {
int[] arr = {10,20,30,10,10,20};
int count=0;
int count1=0;
for(int i=0;i<arr.length;i++)
{
if(arr[i]!=Integer.MIN_VALUE)
{
count=1;
for(int j=i+1;j<arr.length;j++)
{
if(arr[i]==arr[j])
{
count++;
arr[j]=Integer.MIN_VALUE;
}
}
if(count==1)
count1++;
}
}
System.out.println(count1);
}
}

You might also like