Logical and Basic Java - Assignment
Basic Java Questions
1. What is Package?
Package is a group of related classes and interfaces. It helps organize code and avoid name
conflicts.
Example: package [Link];
2. What is a Class?
A class is a blueprint or template used to create objects.
Example:
3. What is an Object?
An object is an instance of a class that contains data and behavior.
Example: Car c = new Car();
4. What is a Method?
A method is a block of code that performs a specific task.
Example:
5. Reverse a number 12345?
Program:
6. Reverse a String?
Program:
7. What is Conditional Statements?
Conditional statements make decisions based on conditions. Example: if, if-else, switch.
Example:
8. What is Control Statements?
Control statements control the flow of execution like loops and decision making.
Example:
9. What is String immutable?
In Java, String is immutable which means once created, its value cannot be changed.
10. What is Array?
Array is a collection of similar type elements stored in contiguous memory.
Example with for-each:
class Car {}
void greet() {
[Link]("Hello");
}
int num = 12345, rev = 0;
while(num != 0){
rev = rev * 10 + num % 10;
num /= 10;
}
[Link](rev);
String str = "hello";
String revStr = "";
for(int i=[Link]()-1;i>=0;i--)
revStr += [Link](i);
[Link](revStr);
int age = 18;
if(age >= 18)
[Link]("Adult");
for(int i=1;i<=5;i++)
[Link](i);
int arr[] = {10,20,30};
for(int n : arr)
[Link](n);
Logical Programs
1. Reverse a String
String s="Java";
String r="";
for(int i=[Link]()-1;i>=0;i--)
r+=[Link](i);
[Link](r);
2. Check Palindrome
String s="madam";
String r="";
for(int i=[Link]()-1;i>=0;i--)
r+=[Link](i);
if([Link](r))
[Link]("Palindrome");
3. Swap Two Numbers (Without 3rd Variable)
int a=5,b=7;
a=a+b;
b=a-b;
a=a-b;
4. Fibonacci Series
int a=0,b=1;
for(int i=0;i<10;i++){
[Link](a+" ");
int c=a+b;
a=b;
b=c;
}
5. Prime Number Check
int n=7, flag=0;
for(int i=2;i<=n/2;i++){
if(n%i==0){
flag=1;
break;
}
}
if(flag==0)
[Link]("Prime");
6. Count Characters in a String
String s="hello";
[Link]([Link]());
7. Find Duplicate Characters
String s="programming";
for(int i=0;i<[Link]();i++){
for(int j=i+1;j<[Link]();j++){
if([Link](i)==[Link](j))
[Link]([Link](j));
}
}
8. Reverse Each Word in a Sentence
String s="Java is fun";
String[] words=[Link](" ");
for(String w:words){
String r="";
for(int i=[Link]()-1;i>=0;i--)
r+=[Link](i);
[Link](r+" ");
}
9. Find Largest Element
int arr[]={4,9,2,7};
int max=arr[0];
for(int n:arr)
if(n>max) max=n;
[Link](max);
10. Print Even Numbers from 1 to 50
for(int i=2;i<=50;i+=2)
[Link](i+" ");