Answers for today's test:::
======================
Method with if condition
public void test(int x) {
int odd = 1;
if (odd) {
System.out.println("odd");
} else {
System.out.println("even");
}
}
Problem:
if (odd)
This is invalid in Java!
Why?
Java does NOT allow non-boolean conditions in if
Unlike C/C++, where:
if (1) → true
if (0) → false
In Java, the if condition must be a boolean expression:
if (true) yes
if (false) yes
if (x > 5) yes
if (odd) false because odd is `int`, not boolean
Correct version:
public void test(int x) {
int odd = 1;
if (odd == 1) {
System.out.println("odd");
} else {
System.out.println("even");
}
}
Program Flow (After Fix):
1. odd = 1
2. Check: odd == 1 → yes true
3. So it prints:
odd
==============================================
What is a Default Constructor?
public class Test { }
This is a simple class with no code.
What is a Default Constructor?
If no constructor is defined, Java automatically provides a:
public Test() { }
Called the default constructor.
Important Points:
It takes no arguments
It is added by compiler
It does nothing internally
As soon as you create any constructor manually, default is not provided
Example Use:
Test obj = new Test(); // This calls the default constructor
=========================================
I. public int a[];
✔️ Valid
Declares an integer array named a
a[] is another way to write [] a
You can also write: int[] a;
II. static int [] a;
✔️ Valid
Declares a static integer array named a
Static means it's shared by the class, not object-specific
III. public [] int a;
Invalid Syntax
In Java, the brackets [] must come after the data type, not before it
Correct: public int[] a;
IV. private int a[3];
Invalid
You cannot specify the array size in the declaration in Java
This is allowed in C/C++, but not in Java
In Java, do like this:
private int[] a = new int[3];
-V. private int[3] a;
Invalid
You cannot write size [3] in the type declaration
Correct format:
private int[] a; // declaration
a = new int[3]; // size initialized later
VI. public final int [] a;
✔️ Valid
Declares a final integer array a
final means: reference to array cannot change
You can't assign a new array
But you can change the values inside it
Example:
a[0] = 10; // allowed
a = new int[5]; // not allowed
==========================================
Line 1:
class Tree {}
This creates a base class called Tree
It’s a parent class or superclass
Think of Tree like a general category (like: All trees 🌳)
Line 2:
class Pine extends Tree {}
Pine is a subclass of Tree
It inherits everything from Tree
So Pine is a Tree.
Line 3:
class Oak extends Tree {}
Oak is another subclass of Tree
Oak also is a Tree, but different from Pine
Line 4:
public class Forest1 {
Declares the main class containing the main() method.
Execution starts here.
Line 5:
public static void main(String[] args) {
Main method: Entry point of the program
Line 6:
Tree tree = new Pine();
What's happening?
A variable named tree is declared with type Tree (parent class)
But we are assigning it a new object: new Pine() (child class)
This is called polymorphism:
> The reference (tree) is of type Tree, but it actually points to a Pine object.
Now:
tree → Pine object
Line 7:
if(tree instanceof Pine)
Checks whether the object tree is an instance of the Pine class.
Since:
tree = new Pine();
This condition is true
So, it goes inside this if block
Line 8:
System.out.println("Pine");
Since the condition was true, this line is executed.
Output:
Pine
Rest of the code is not executed because if already matched:
else if(tree instanceof Tree) // skipped
else if(tree instanceof Oak) // skipped
else // skipped
Final Output:
Pine
Program Flow:
Step-- Code-- What Happens
1 -->Tree tree = new Pine(); -->A Pine object is created but referenced as Tree
2 -->tree instanceof Pine -- True →--> object is actually of type Pine
3 -->System.out.println("Pine"); --->Prints Pine to output
4 -->All other else if blocks--> --> Skipped
Business::
Think of this:
Tree = General class of employees
Pine = Developer
Oak = Designer
You hire a Developer, but you assign them to a general Employee reference.
You later check:
"Is this employee a Developer?" → ✅ Yes, so you print Developer.
Concepts Used in This Program:
Concept--> Meaning
Class & Inheritance--> Pine and Oak extend Tree
Polymorphism--> Tree tree = new Pine();
instanceof operator -->To check actual object type at runtime
Conditional if-else--> Executes only the first true block
=========================================
Line 1:
String x = "xyz";
What it does:
Creates a String variable named x
Stores the value "xyz" in it
Now:
x = "xyz"
Line 2:
x.toUpperCase(); // Line 2 – no assignment
What it does:
Tries to convert the string to uppercase
But it does NOT assign the result to anything
So x remains unchanged
Important:
Strings in Java are immutable
x.toUpperCase() returns "XYZ" but it’s not stored
So still:
x = "xyz"
Line 3:
String y = x.replace('Y', 'y');
What it does:
Calls replace('Y', 'y') on string x
But:
x = "xyz"
There’s no capital 'Y' in "xyz"
So, the replace() does nothing, returns the same string
So:
y = "xyz"
Line 4:
y = y + "abc";
What it does:
Adds (concatenates) "abc" to the current value of y
Current:
y = "xyz"
So:
y = "xyz" + "abc" → "xyzabc"
Final:
y = "xyzabc"
Line 5:
System.out.println(y);
What it does:
Prints the final value of y to the console
Final Output:
xyzabc
========================================={
import java.util.*;
public class KennyCoolDrinks {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt(); // Step 1
int[] prices = new int[n]; // Step 2
for (int i = 0; i < n; i++) { // Step 3
prices[i] = sc.nextInt();
}
int t = sc.nextInt(); // Step 4
for (int testCase = 0; testCase < t; testCase++) { // Step 5
int m = sc.nextInt(); // Step 6
int p = sc.nextInt(); // Step 7
int count = 0; // Step 8
for (int i = 0; i < n; i++) { // Step 9
if (prices[i] <= p) { // Step 10
count++;
}
}
System.out.print(testCase + " " + count + " "); // Step 11
}
}
}
=====≠==================================
Above program flow::::
===================
import java.util.*
This line imports the Scanner class from Java's utility package, which lets us read input from the keyboard or console.
public class KennyCoolDrinks {
Declares the main class of the program. You can name it anything, but here it's named KennyCoolDrinks.
public static void main(String[] args) {
This is the starting point of the Java program. The JVM (Java Virtual Machine) begins execution here.
Scanner sc = new Scanner(System.in);
Creates a Scanner object named sc, which reads user input from the keyboard (console).
Example: If user types 5, then sc.nextInt() will read that 5.
int n = sc.nextInt();
Reads the number of shops Kenny wants to check.
Example Input:
5
Now: n = 5 → there are 5 shops
int[] prices = new int[n];
Creates an array of integers named prices, with n elements, to store the Coca Cola price at each shop.
for (int i = 0; i < n; i++) { prices[i] = sc.nextInt(); }
Reads the price at each shop, and stores it in the prices array.
Example Input:
3 10 8 6 11
Now:
prices[0] = 3
prices[1] = 10
prices[2] = 8
prices[3] = 6
prices[4] = 11
int t = sc.nextInt();
Reads the number of test cases (scenarios), meaning how many different money amounts Kenny will try.
Example Input:
2
Now: t = 2 → Two test cases will follow
for (int testCase = 0; testCase < t; testCase++) {
Starts a loop to process each test case one by one.
First time → testCase = 0
Second time → testCase = 1
int m = sc.nextInt();
Reads the number of days Kenny wants to buy the drink.
We do not use this value in our logic (it's ignored).
Example Input for test case 0:
1
int p = sc.nextInt();
Reads the money Kenny has per day.
This value is used to check affordability.
Example Input:
10
So Kenny has ₹10 per day in test case 0.
int count = 0;
Initializes a counter to count how many shops Kenny can afford in this test case.
for (int i = 0; i < n; i++) { if (prices[i] <= p) { count++; } }
Goes through each shop:
Checks if the price of that shop is less than or equal to Kenny’s daily money p
If true, increases the count
For example:
If p = 10 and prices = {3, 10, 8, 6, 11},
→ Kenny can buy from shops at index 0, 1, 2, 3
→ So, count = 4
System.out.print(testCase + " " + count + " ");
Prints the result for the current test case in this format:
test_case_number count
For test case 0: 0 4
For test case 1: 1 5
Final Output:
0 4 1 5
Final Output:::
0 4 → Test case 0 → Kenny can buy from 4 shops
1 5 → Test case 1 → Kenny can buy from 5 shops
Flow Diagram (Simplified)::
INPUT
↓
Number of shops → shop prices → number of test cases
↓
For each test case:
→ Read daily money
→ Loop through shops
→ Count how many prices ≤ daily money
→ Print test case number and count
↓
END
Business::
Let’s say Kenny is a customer:
He checks multiple daily budgets.
You (as a developer) write a program to help him filter which vendors are affordable under each budget.
=========================================
For each test case, print:
Test Case Number --> Count of shops--> Kenny can afford
Let's Process Test Case by Test Case:
Test Case 0 → 1 10
> Meaning: Kenny wants to buy for 1 day, and has ₹10 that day.
We don’t care about the number of days here.
We only care about:
Which shop has price ≤ 10
Shop Prices:
Index → 0 1 2 3 4
Price → 3 10 8 6 11
Step-by-step Check:
Shop Index--> Price--> Can Kenny afford?
0 -->3 -->Yes (3 ≤ 10)
1 -->10 --> Yes (10 ≤ 10)
2 -->8--> Yes (8 ≤ 10)
3 --->6 --->Yes (6 ≤ 10)
4 --->11 --> No (11 > 10)
Total valid shops = 4
So we print:
0 4
0 → test case 0
4 → 4 valid shops
Test Case 1 → 3 11
> Kenny has ₹11 per day
Step-by-step Check:
Shop Index Price Can Kenny afford?
0 3 Yes (3 ≤ 11)
1 10 Yes (10 ≤ 11)
2 8 Yes (8 ≤ 11)
3 6 Yes (6 ≤ 11)
4 11 Yes (11 ≤ 11)
Total valid shops = 5
So we print:
1 5
1 → test case 1
5 → 5 valid shops
Final Output:
0 4 1 5
Value --Meaning
0-- Test case 0
4 --4 shops can be afforded in test 0
1 --Test case 1
5-- 5 shops can be afforded in test 1
Summary:
Test Case 0:
→ Kenny has ₹10
→ Shops affordable = 0, 1, 2, 3 (4 shops)
→ Print: 0 4
Test Case 1:
→ Kenny has ₹11
→ Shops affordable = all (5 shops)
→ Print: 1 5
Concepts Behind the Output:
Concept-- Used for...
Loop --To go through each shop
Condition --To check if rate ≤ p
Counter-- To count how many shops are affordable
Index Print --To show which test case it is (0, 1, etc.)
Output:: 0 4 1 5
=========================================
Java Concepts Used:
Concept -->How It’s Used in Program
Arrays -->To store shop prices
Loops (for) -->To read input and check each shop
Conditionals (if) -->To check if shop rate ≤ p
Scanner -->To read input from user
while loop -->To process multiple test cases
Example:
A subscription app wants to check which vendors' prices are affordable for a customer’s daily budget.
Each test case represents a different customer or different day
Helps in filtering shops or creating purchase recommendations
Summary::::
You count how many shops have rate ≤ Kenny’s daily budget (p)
The output format is:
test_case_number count
That’s why the output is: 0 4 1 5
=======================================
Sample Input:
5
3 10 8 6 11
4
10
Let’s break this down:
Input Line -->Meaning
5 -->Total number of shops n = 5
3 10 8 6 11 -->Rates of cool drinks in each shop
4 -->Number of days m = 4
10 -->Money Kenny has each day, p = 10
========================================
No comments:
Post a Comment