java all test
java all test
3]
public class Demo {
static int a = test();
//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
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{
====================================================
ENCAPSULATOIN
===================================================================================
===================
1]
public class Account
{
A) 100
B) 50
C) 150 [correct]
D) 100
2]
package test2;
public class BankAcc
{
private int pin=1234;
3]
public class Student
{
private long phoneno;
public Student()
{
setPhoneno(7356481687l);
}
===================================================================================
=====================
4]
class Base {
}
class Child extends Base {
A) Child
B) Base
C) Compilation error
D) Runtime error
Answer: B) Base
5]
public class A
{
int x=10;
public static void m1(B b)
{
System.out.println(b.y);
}
}
public class B
{
int y=20;
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;
}
}
A) null
B) Compilation error
C) V8
D) Runtime exception
Answer: C) V8
class Truck {
private Engine engine = new Engine( );
A) Diesel
B) Electric
C) null
D) Compilation error
Answer: B) Electric
9]
class Address {
String city = "Chennai";
}
class Person {
private Address addr = new Address( );
Address getAddress( ) {
return addr;
}
}
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( );
}
}
11]
public class Parent {
public Parent(int i) {
this.i = i;
}
static {
Parent parent = new Child();
parent.m1();
}
-----------------------------------------------------------------------------------
-------
public class Child extends Parent {
C) ClassCastException
D) 10
1000
12]
class Parent {
int x = getX( );
public Parent( ) {
System.out.println("Parent Constructor: " + x);
}
public Child( ) {
System.out.println("Child Constructor: " + super.x);
}
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 {
A) Bike ride
B) Car drive
C) Compilation error
D) Runtime ClassCastException
14]
class X {
}
class Y extends X {
}
class Z extends X {
A) Prints “Done”
B) Compile-time error
C) ClassCastException at runtime
D) No output, program ends normally
15]
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 {
=============================
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.
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{
===============================
1.
class Account {
private int balance = 1000;
✅ **Answer: C. 1500**
===================================================================================
==========================================
2.class Account {
private int balance = 1000;
public void deposit(int amount) {
if (amount > 0) {
balance += amount;
}
}
A. 800
B. 1000
C. 1700
D. 1700
✅ Answer: C. 1700
===================================================================================
=================================
Copying the Object Reference (3 Questions)
3.
class Counter {
int count = 0;
}
✅ **Answer: B. 6
===================================================================================
=============================================
4.
class Pen {
String color;
}
5.
class Engine {
String status = "OFF";
}
class Mechanic {
static void startEngine(Engine e) {
e.status = "ON";
}
}
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 {}
a) Class A
b) Class B ✅
c) Compilation error
d) Runtime error
7.
class Animal
{
void sound()
{
System.out.println("Animal sound");
}
}
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 {}
A. true
B. false
C. Compilation Error
D. Runtime Error
✅ Answer: A. true
===================================================================================
=================
10.
class Parent {
Parent() {
System.out.println("Parent");
}
}
===================================================================================
====================
11.
class A {
int i = 10;
}
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");
}
A. null
B. Java Basics
C. Book
D. Compilation Error
13.class Wheel {
int size = 16;
}
class Bike {
Wheel frontWheel = new Wheel();
Wheel backWheel = new Wheel();
}
A. 16
B. 32
C. 0
D. Compilation Error
✅ Answer: B. 32
===================================================================================
===============================
14.
class Address {
String city = "New York";
}
class Person {
Address address;
}
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();
}
}
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.
Explanation:
Average delivery time = (3+5+2+6+4+3) / 6 = 23 / 6 ≈ 3.83
Faster deliveries = [3, 2, 3] → Count = 3
Explanation:
Average = 7.0 → No delivery is strictly less than average
Explanation:
Average = (1+2+3)/3 = 2.0 → Only 1 is strictly less than 2
Solution:
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]).
Return the modified array after processing all overlapping pairs in one left-to-
right pass.
🔁 Rules:
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:
SOLN:
====
import java.util.Scanner;
class Main {
public static void main(String []args){
Scanner s= new Scanner(System.in);
int size=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;
No output
Hello world
run time error
compile time error
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
public scope
default scope
same as class scope
protected scope
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
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);
}
}