Java - Practice Book
Java - Practice Book
By Srinivas Garapati
Address : Door No. 301, 3rd Floor, Sri Sai Arcade, Satyam Theatre Rd, beside Aditya Trade Centre,
Kumar Basti, Ameerpet, Hyderabad, Telangana 500018. Contact – 911 955 67898
Ameerpet Technologies
Java Practice Book
Java - Introduction
1Who developed the Java programming language?
a) Bill Gates b) James Gosling
c) Linus Torvalds d) Tim Berners-Lee
Which of the following is true about the Java Virtual Machine (JVM)?
a) Converts Java code to machine code during runtime. b) It is platform dependent.
c) It is responsible for memory management d) It is a physical machine where Java program run.
What is the purpose of the 'public static void main(String[] args)' method in Java?
a) It is the entry point of a Java program. b) It defines a new class in Java.
c) It is used for mathematical calculations. d) It is a utility method for file I/O operations.
Java - Variables
Account Patient
___________ accnum = __________________ ___________ name = __________________
___________ name = __________________ ___________ ward = __________________
___________ age = __________________ ___________ age = __________________
___________ balance = __________________ ___________ disease = __________________
___________ pin = __________________ ___________ vaccinated= _________________
___________ married = __________________ ___________ married = __________________
___________ gender = __________________ ___________ hospital = __________________
___________ IFSC = __________________ ___________ billDue = __________________
___________ mail = __________________ ___________ doctor = __________________
___________ address = __________________ ___________ address = __________________
Text Book Mobile
___________ name = __________________ ___________ mobile = __________________
___________ price = __________________ ___________ model = __________________
___________ pages = __________________ ___________ color = __________________
___________ author = __________________ ___________ price = __________________
___________ ISBN = __________________ ___________ ram = __________________
___________ publisher = __________________ ___________ earphones= _________________
___________ dimension= ________________ ___________ screen = _________________
Define Variable?
What is the default value of an integer variable in Java if it is not initialized explicitly?
a) 0 b) -1 c) Null d) Error
We need to specify the datatype only once in variable creation(not everytime in use):
public class Code
{
public static void main(String[] args) {
int a=10;
int a=20;
System.out.println(a);
}
}
Arithmetic Operators
sum=sum+n%10; rev=rev*10+n%10;
n=n/10; n=n/10;
sum=sum+n%10; rev=rev*10+n%10;
n=n/10; n=n/10;
sum=sum+n%10; rev=rev*10+n%10;
n=n/10; n=n/10;
Evaluate Expressions
7+2-3 7-3+2 7*2/3
7*3%2 7-3%5 (7+2)/3
(7-3)%2 5/3 + 5%3 3/5 + 3%5
5+3/2*4-8%3+2 (5+3)/2*4-8%(3+2)
14. Condition for sqare of first num equals to cube of the second num
16. Condition for the last digits of given 2 nums are same
17. Condition for sum of last digits of given three nums is equal to 10
18. Condition for sum of first 2 nums last digits equals to square of the 3rd num
19. Condition for First and Second nums are euqal when we remove last digit of second num:
22. Condition for the sum of First 2 numbers equals to last digit of 3rd num
12. Program to calculate the total amount for the given quantity of fruits purchased
13. Program to Find the Total salary for the given basic salary
Formatting Output
• An output without format doesn’t make sense to the end user.
• We always display results in string format.
• We need to create formatted string with output values as follows
Syntax Example
int + int = int 10 + 20 => 30
String + String = String "Java" + "Book" => JavaBook
"10" + "20" => 1020
String + int = String "Book" + 5 => Book5
"123" + 456 => 123456
String + int + int = String "Sum = " + 10 + 20 => Sum = 1020
String + (int + int) = String "Sum = " + (10 + 20) => Sum = 30
String + double = String "Value = " + 23.45 => Value = 23.45
String – int = Error
}
}
Output: A value = 10
}
}
Output: 10
20
}
}
Output: a val : 10
b val : 20
}
}
Output : 10, 20
}
}
Output: 10 20
}
}
Output: 5 + 2 = 7
5–2=3
5 * 2 = 10
5/2=2
5%2=1
3. Condition for the first number less than the second number and greater than the third number?
5. Condition for the first number is even and the second number is odd?
13. Condition for the all three numbers equal to each other?
14. Condition for at least two numbers among the three equal to each other?
15. Condition for the all three numbers different from each other?
Scanner Class:
• Using java library class Scanner, we can read input like integers, characters, strings, double values
from the user.
• Different methods to read different values such as nextInt(), next(), nextDouble()…
• We need to specify the Keyboard(System.in) while creating Scanner class object.
Scanner scan = new Scanner(System.in);
• We access all the methods using object reference name.
Reading integer value: nextInt() method read and returns an integer value
import java.util.Scanner;
public class Code
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.print("Enter integer : ");
int n = scan.nextInt();
System.out.println("Input value is : " + n);
}
}
Output: Enter integer : 10
Input value is : 10
Reading Boolean value: nextBoolean() method returns Boolean value that we entered
import java.util.Scanner;
public class Code
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.print("Enter boolean value : ");
boolean b = scan.nextBoolean();
System.out.println("Input value is : " + b);
}
}
Output: Enter Boolean value : true
Input value is : true
Reading String: using next() method we can read single word string from the user
import java.util.Scanner;
public class Code
{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter your name : ");
String name = scan.next();
System.out.println("Hello : " + name);
}
}
Output: Enter your name: Amar
Hello : Amar
Reading character:
import java.util.Scanner;
class Code {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter character : ");
char ch = scan.next().charAt(0);
System.out.println("Input character is : " + ch);
}
}
If Block Programs
If Block: Execute a block only if the specified condition is valid.
Syntax Flow Chart
if(Condition)
{
If-block-logic;
}
Program to give 15% discount on bill if the bill amount is greater than 5000
import java.util.Scanner;
public class Code{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter bill : ");
double bill = scan.nextDouble();
if(bill>=5000){
double discount = 0.15 * bill;
bill = bill-discount;
}
Program to give 20% bonus on salary if the employee has more than 5 years of experience:
Give 10% discount on total purchase if the customer is a member & the bill amount is greater than 1000.
Program to give a 15% discount on hotel booking if the stay duration is more than 7 days.
Give a 10% discount on grocery items if the total quantity purchased is more than 20.
Give a 5% bonus on salary if the employee's attendance is perfect for the month (no absences).
Program to give a 20% discount on gym membership if the customer signs up for a year.
Program to give 200 Cash back to and add to credit card amount if the user pay min 50% of credit card
bill amount. Display final limit of Credit Card.
Else Block: It executes when the given condition of if block fails. Else block is optional for if block. Else
block cannot be defined without IF block.
Syntax Flow Chart
if(condition)
{
If-stats;
}
else
{
Else-stats;
}
if(
System.out.println("Even number");
else
}
}
If Else If block
If else if: The if-else-if ladder statement executes only block among multiple we defined based on valid
condition.
Syntax Flow Chart
if(condition1){
Statement1;
}
else if(condition2){
Statement2;
}
else if(condition3){
Statement3;
}
else{
Statement4;
}
class Code
{
public static void main(String[] args)
{
System.out.println("b is big");
else
System.out.println("c is big");
}
}
Output: Enter a, b, c values :
10
30
20
b is big
import java.util.Scanner;
class Code
{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter number of units : ");
int units = sc.nextInt();
double bill=0.0;
if(units>=0 && units<=100)
bill = units*0.8;
else if(units>100 && units<=200)
else
Nested If Block
Nested If: Defining if block inside another if block.
Syntax Flow Chart
if(condition){
if(condition){
if-if-Stat;
}
else{
if-else-stat;
}
}
else{
if(condition){
else-if-stat;
}
else{
else-else-
stat;
}
}
Nested If Programs
Check Even Number or Not only if it is Positive
import java.util.Scanner;
class Code
{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter number : ");
int n = scan.nextInt();
if(n>0){
if(n%2==0)
System.out.println("Even number");
else
System.out.println("Not even number");
}
else{
System.out.println("Negative number given");
}
}
}
Output: Enter number: 5
Not even number
int a = scan.nextInt();
int b = scan.nextInt();
int c = scan.nextInt();
if(
System.out.println("Equilateral");
else if(
System.out.println("Isosceles");
else
System.out.println("Scalene");
}
}
Output: Enter 3 sides of triangle :
70
70
40
Isosceles
Introduction to Loops
Note: Block executes only once whereas Loop executes until condition become False
For Loop: We use for loop only when we know the number of repetitions. For example,
• Print 1 to 10 numbers
• Print Array elements
• Print Multiplication table
• Print String character by character in reverse order
While loop: We use while loop when we don’t know the number of repetitions.
• Display contents of File
• Display records of Database table
Do while Loop: Execute a block at least once and repeat based on the condition.
• ATM transaction: When we swipe the ATM card, it starts the first transaction. Once the first
transaction has been completed, it asks the customer to continue with another transaction and
quit.
For Loop
for loop: Execute a block of instructions repeatedly as long as the condition is valid. We use for loop only
when we know the number of iterations to do.
Syntax Flow Chart
Print numbers 2, 4, 6, 8, 10
Program to print numbers divisible by 4 and not divisible by 100 from 100 to 300
While Loop
While loop: Execute a block of instructions repeatedly until the condition is false. We use while loop only
when don’t know the number of iterations to do.
while(condition)
{
statements;
}
if(num%2==0)
System.out.println(num + " is even.");
else
System.out.println(num + " is odd.");
System.out.println("5. exit");
Program to find the sum of first and last digits in the given number:
int n = 321875;
Program to display multiplication table for each digit in the given number:
int n = 321875;
Program to find factorial value for each digit in the given number:
int n = 321875;
Program to display square and cube values for each digit in the given number:
int n = 321875;
Palindrome Number: The number become same when we reverse is called Palindrome number
Examples: 121, 1001, 123321
Program to find the power value of given digit by reading input values.
For example, int n=3 and p=4; → Find 3^4 value
Program to find the square root value for the given number without library method:
int n = 144 → ans = 12
class Code
{
public static void main(String[] args)
{
int num=9657, sum, dig;
System.out.print(num + "->");
while(num/10!=0)
{
sum = 0;
while(num!=0){
dig=num%10;
sum+=dig;
num/=10;
}
System.out.print(sum + "->");
num=sum;
}
}
}
ADAM Number: Take a number then square it then reverse it then find its square root then reverse. If the
given number equals to the final number then it is called ADAM.
• Take the number (12)
• Square the number (144)
• Reverse the number(441)
• Square root of number (21)
• Reverse the number(12)
import java.util.Scanner;
class Code{
public static void main(String[] args){
int num, temp, r1, r2, sq, rev1 = 0, rev2 = 0;
Scanner scan = new Scanner(System.in);
System.out.print("Enter Num : ");
num = scan.nextInt();
temp = num * num;
System.out.println("Square of the num : " + temp);
while (temp != 0){
r1 = temp % 10;
rev1 = rev1 * 10 + r1;
temp = temp / 10;
}
System.out.println("Reverse Num : " + rev1);
sq = (int)Math.sqrt(rev1);
System.out.println("Sqrt num : " + sq);
while (sq != 0){
r2 = sq % 10;
rev2 = rev2 * 10 + r2;
sq = sq / 10;
}
System.out.println("Reverse Num : " + rev2);
if (rev2 == num)
System.out.println(num + " is an Adam number");
else
System.out.println(num + " is not an Adam number");
}
}
break: A branching statement that terminates the execution flow of a Loop or Switch case.
class Code
{
public static void main(String[] args) {
for (int i=1 ; i<=10 ; i++){
if(i==5){
break;
}
System.out.print(i + " ");
}
}
}
Output: 1 2 3 4
Continue: A branching statement that terminates the current iteration of loop execution.
class Code
{
public static void main(String[] args) {
for (int i=1 ; i<=10 ; i++){
if(i==5){
continue;
}
System.out.print(i + " ");
}
}
}
Output: 1 2 3 4 5 6 7 8 9 10
Switch case
Switch: is a Conditional Statement executes based on given choice (case). Default case executes if the
user entered invalid choice. Case should terminate with break statement.
Syntax FlowChart
switch(choice)
{
case 1 : Statements ;
break
case 2 : Statements ;
break
......
case n : Statements ;
break
default: Statements ;
}
import java.util.Scanner;
class Code
{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter character(r, g, b) : ");
char ch = sc.next().charAt(0);
switch(ch)
{
case 'r' : System.out.println("Red");
break;
case 'g' : System.out.println("Green");
break;
case 'b' : System.out.println("Blue");
break;
default : System.out.println("Weird");
}
}
}
Do-While Loop
do-while: Executes a block at least once and continue iteration until condition is false.
do
{
statements;
} while(condition);
Number of iterations in Nested loop is equals to “outer loop iterations multiplied by inner loop
iterations”.
class Code
{
public static void main(String[] args)
{
int count=0;
for (int i=1 ; i<=5 ; i++)
{
for (int j=1 ; j<=5 ; j++)
{
count++;
}
}
System.out.println("Number of Iterations : " + count);
}
}
Pattern Programs
Pattern:
• Representation of data in two-dimensional format (rows and columns)
• We use nested loops to print patterns.
• We can print patterns with numbers, characters, starts, symbols
• Patterns can be in different shapes like triangle, rectangle, half triangle, pyramid and so
on.
Pattern Logic
for (int i=1 ; i<=5 ; i++)
{
11111
for (int j=1 ; j<=5 ; j++)
22222
33333 {
44444 System.out.print(i);
55555 }
System.out.println();
}
Pattern Logic
for (int i=1 ; i<=5 ; i++)
{
*****
for (int j=1 ; j<=5 ; j++)
*****
***** {
***** System.out.print("*");
***** }
System.out.println();
}
Pattern Logic
for (int i=5 ; i>=1 ; i--)
54321 {
54321
for (int j=5 ; j>=1 ; j--){
54321
54321 System.out.print(j);
54321 }
System.out.println();
}
}
Pattern Logic
for (int i=5 ; i>=1 ; i--)
55555 {
44444
for (int j=5 ; j>=1 ; j--)
33333
22222 {
11111 System.out.print(i);
}
System.out.println();
}
Pattern Logic
for (int i=1 ; i<=5 ; i++)
10101 {
10101
for (int j=1 ; j<=5 ; j++)
10101
10101 {
10101
}
System.out.println();
}
Pattern Logic
for (int i=1 ; i<=5 ; i++)
11111 {
00000
for (int j=1 ; j<=5 ; j++)
11111
00000 {
11111
}
System.out.println();
}
Pattern Logic
for (int i=1 ; i<=5 ; i++){
for (int j=1 ; j<=5 ; j++){
$#$#$
if(j%2==0)
$#$#$
$#$#$ System.out.print(
$#$#$ else
$#$#$ System.out.print(
}
System.out.println();
}
Pattern Logic
int k=1;
12345 for (int i=1 ; i<=5 ; i++){
67891
for (int j=1 ; j<=5 ; j++){
23456
78912 System.out.print(k++%10);
34567 }
System.out.println();
}
Pattern Logic
for (int i=1 ; i<=5 ; i++)
{
11111
for (int j=1 ; j<=5 ; j++){
12345
33333 if(
12345 System.out.print(j);
55555 else
System.out.print(i);
}
System.out.println();
}
Pattern Logic
for (int i=1 ; i<=5 ; i++)
{
55555
for (int j=1 ; j<=5 ; j++){
54321
33333 if(
54321 System.out.print(j);
11111 else
System.out.print(i);
}
System.out.println();
}
Pattern Logic
for (int i=1 ; i<=7 ; i++){
+++++++ for (int j=1 ; j<=7 ; j++){
+ + +
if(
+ + +
+++++++ Printf("+");
+ + + else
+ + + Printf(" ");
+++++++ }
Printf(“\n”);
}
Pattern Logic
for (int i=1 ; i<=7 ; i++){
+ for (int j=1 ; j<=7 ; j++){
+
if(
+
+ Printf("+");
+ else
+ Printf(" ");
+ }
Printf(“\n”);
}
Pattern Logic
+ for (int i=1 ; i<=7 ; i++){
+ for (int j=1 ; j<=7 ; j++){
+
if(
+
+ Printf("+");
+ else
+ Printf(" ");
}
Printf(“\n”);
}
Pattern Logic
for (int i=1 ; i<=7 ; i++){
+ + for (int j=1 ; j<=7 ; j++){
+ +
if(
+ +
+ Printf("+");
+ + else
+ + Printf(" ");
+ + }
Printf(“\n”);
}
Pattern Logic
for (int i=1 ; i<=7 ; i++){
+ + + + + + + for (int j=1 ; j<=7 ; j++){
+ + + +
if(
+ + + +
+ + + Printf("+");
+ + + + else
+ + + + Printf(" ");
+ + + + + + + }
Printf(“\n”);
}
Pattern Logic
for (int i=1 ; i<=7 ; i++){
++++ for (int j=1 ; j<=7 ; j++){
+
if(
+
+ Printf("+");
+ else
+ Printf(" ");
++++ }
Printf(“\n”);
}
+ for (int i=1 ; i<=7 ; i++){
+ for (int j=1 ; j<=7 ; j++){
+
if(
+++++++
+ Printf("+");
+ else
+ Printf(" ");
}
Printf(“\n”);
}
for (int i=1 ; i<=7 ; i++){
++++ + for (int j=1 ; j<=7 ; j++){
+ +
if(
+ +
+++++++
+ + Printf("+");
+ + else
+ ++++ Printf(" ");
}
Printf(“\n”);
}
Pattern Logic
+ + + + + for (int i=1 ; i<=7 ; i++){
+ for (int j=1 ; j<=5 ; j++){
+
if(
+ + + + +
+ Printf("+");
+ else
+ + + + + Printf(" ");
}
Printf(“\n”);
}
Pattern Logic
+ + + + + for (int i=1 ; i<=7 ; i++){
+ for (int j=1 ; j<=5 ; j++){
+
if(
+ + + + +
+ Printf("+");
+ else
+ + + + + Printf(" ");
}
Printf(“\n”);
}
Pattern Logic
+ for (int i=1 ; i<=7 ; i++){
+ + for (int j=1 ; j<=7 ; j++){
+ +
if(
+ +
+ + + + + + + + Printf("+");
+ else
+ Printf(" ");
}
Printf(“\n”);
}
Pattern Logic
+ + + + + for (int i=1 ; i<=7 ; i++){
+ for (int j=1 ; j<=5 ; j++){
+
if(
+ + + + +
+ Printf("*");
+ else
+ + + + + Printf(" ");
}
Printf(“\n”);
}
Pattern Logic
+ + + + + for (int i=1 ; i<=7 ; i++){
+ for (int j=1 ; j<=5 ; j++){
+
if(i==1||j==1||i==4||i==7||(j==5&&i>=4))
+ + + + +
+ + Printf("*");
+ + else
+ + + + + Printf(" ");
}
Printf(“\n”);
}
Pattern Logic
for (int i=1 ; i<=7 ; i++){
+ + + + + + for (int j=1 ; j<=5 ; j++){
+
if(
+
+ Printf("*");
+ else
+ Printf(" ");
}
Printf(“\n”);
}
Pattern Logic
+ + + + + for (int i=1 ; i<=7 ; i++){
+ + for (int j=1 ; j<=5 ; j++){
+ +
if(i==1||i==4||i==7||j==1||j==5)
+ + + + +
+ + Printf("*");
+ + else
+ + + + + Printf(" ");
}
Printf(“\n”);
}
Pattern Logic
+ + + + + for (int i=1 ; i<=7 ; i++){
+ + for (int j=1 ; j<=5 ; j++){
+ +
if(
+ + + + +
+ Printf("*");
+ else
+ + + + + Printf(" ");
}
Printf(“\n”);
}
Patterns – All Alphabets
+ for (int i=1 ; i<=5 ; i++){
+ + for (int j=1 ; j<=9 ; j++){
+ +
if(
+ + + +
+ + Printf("+");
+ + else
Printf(" ");
}
Printf(“\n”);
}
Pattern Logic
+ + + + for (int i=1 ; i<=7 ; i++){
+ + for (int j=1 ; j<=7 ; j++){
+ +
if((j==1)||(i==1&&j<=6)||(i==4&&j<=6)||(i==7&&j<=6
+ + + +
+ + )||(j==7&&i>1&&i<4)||(j==7&&i>4&&i<7))
+ + Printf("+");
+ + + + else
Printf(" ");
}
Printf(“\n”);
}
Pattern Logic
+ + + + + for (int i=1 ; i<=7 ; i++){
+ for (int j=1 ; j<=7 ; j++){
+
if(i==1||j==4||i==j+3)
+ +
+ + Printf("+");
+ else
Printf(" ");
}
Printf(“\n”);
}
Pattern Logic
for (int i=1 ; i<=7 ; i++){
+ + for (int j=1 ; j<=7 ; j++){
+ +
if(j==1||(j==6-i)||(i==2+j))
+ +
+ Printf("+");
+ + else
+ + Printf(" ");
+ + }
Printf(“\n”);
}
Pattern Logic
+ + for (int i=1 ; i<=7 ; i++){
+ + + + for (int j=1 ; j<=7 ; j++){
+ + + +
if(j==1||j==7||(i==j&&j<=4)||(j==8-i&&j>4))
+ + +
+ + Printf("+");
+ + else
+ + Printf(" ");
}
Printf(“\n”);
}
Pattern Logic
+ + for (int i=1 ; i<=7 ; i++){
+ + + for (int j=1 ; j<=7 ; j++){
+ + +
if(j==1||j==7||(i==j))
+ + +
+ + + Printf("+");
+ + + else
+ + Printf(" ");
}
Printf(“\n”);
}
1
12
123
1234
12345
Pattern Logic
1
21
321
4321
54321
Pattern Logic
12345
1234
123
12
1
Pattern Logic
12345
2345
345
45
5
Pattern Logic
5
54
543
5432
54321
Pattern Logic
5
45
345
2345
12345
Pattern Logic
54321
5432
543
54
5
Pattern Logic
54321
4321
321
21
1
Pattern Logic
1
22
333
4444
55555
Pattern Logic
11111
2222
333
44
5
Pattern Logic
5
44
333
2222
11111
Pattern Logic
55555
4444
333
22
1
Pattern Logic
1
23
456
7891
23456
Pattern Logic
12345
6789
123
45
6
Pattern Logic
for (int i=1 ; i<=5 ; i++){
for (int j=i ; j<5 ; j++){
1
Printf(“ “);
21
321 }
4321 for (int k=i ; k>=1 ; k--){
54321 Printf(“%d”, k);
}
Printf(“\n”);
}
Pattern Logic
12345
1234
123
12
1
Pattern Logic
12345
2345
345
45
5
Pattern Logic
5
45
345
2345
12345
Pattern Logic
5
54
543
5432
54321
Pattern Logic
54321
4321
321
21
1
Pattern Logic
54321
5432
543
54
5
Characters Triangle Patterns
Pattern Logic
A
AB
ABC
ABCD
ABCDE
Pattern Logic
A
BA
CBA
DCBA
EDCBA
Pattern Logic
ABCDE
ABCD
ABC
AB
A
Pattern Logic
ABCDE
BCDE
CDE
DE
E
Pattern Logic
E
ED
EDC
EDCB
EDCBA
Pattern Logic
E
DE
CDE
BCDE
ABCDE
EDCBA
EDCB
EDC
ED
E
EDCBA
DCBA
CBA
BA
A
Pattern Logic
*****
****
***
**
*
Pattern Logic
*
**
***
****
*****
Pattern Logic
*****
****
***
**
*
Pattern Logic
*
**
***
****
*****
****
***
**
*
Pattern Logic
for(int i=1 ; i<10 ; i++){
if(i<=5){
for(int x=i ; x<=5 ; x++){
Printf(“ “);
}
* for(int j=1 ; j<=i ; j++){
** Printf(“*”);
*** }
**** Printf(“\n”);
***** }
****
else{
***
for(int x=i ; x>=5 ; x--){
**
Printf(“ “);
*
}
for(int k=i ; k<10 ; k++){
Printf(“*”);
}
Printf(“\n”);
}
}
*****
****
***
**
*
**
***
****
*****
*****
****
***
**
*
**
***
****
*****
Pattern Logic
10101
0101
010
10
1
Pattern Logic
1
10
101
1010
10101
Pattern Logic
1
00
111
0000
11111
Pattern Logic
11111
0000
111
00
1
Pattern Logic
*
**
* *
* *
* *
* *
* *
********
Pattern Logic
********
* *
* *
* *
* *
* *
**
*
Pattern Logic
********
* *
* *
* *
* *
* *
**
*
Pattern Logic
*
**
* *
* *
* *
* *
* *
********
Pyramid Patterns
Pattern Logic
*
***
*****
*******
*********
Pattern Logic
*
* *
* *
* *
*********
Pattern Logic
1
222
33333
4444444
555555555
*********
*******
*****
***
*
Pattern Logic
*********
* *
* *
* *
*
Pattern Logic
555555555
4444444
33333
222
1
Pattern Logic
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
123454321
1234321
12321
121
1
Pattern Logic
1
121
12321
1234321
123454321
Pattern Logic
123454321
1234321
12321
121
1
Pattern Logic
1
212
32123
4321234
543212345
Arrays
Declare Array Variable
Find the sum of odd elements in the given array using for-each loop:
Int[] arr = {3, 7, 8, 2, 5, 6, 4};
Swap first and second elements in the array then print elements using for-each loop:
Int[] arr = {3, 7, 8, 2, 5, 6, 4};
Swap first and last elements in the array then print elements using for-each loop:
Int[] arr = {3, 7, 8, 2, 5, 6, 4};
Swap array element with its adjecnt element for the specified location:
Int[] arr = {3, 7, 8, 2, 5, 6, 4};
Int loc = 3;
Create 2 new arrays with even and odd numbers from the given mixed elements array:
Int[] arr = {3, 7, 8, 2, 5, 6, 4};
Display array elements which are greater than average of all elements in the array:
Int[] arr = {3, 7, 8, 2, 5, 6, 4};
Merge 2 arrays:
Int[] a1 = {3, 7, 8, 2,};
Int[] a2 = {5, 6, 4};
Create the array by reading size and fill the array with elements by reading again from user:
Program to arrange even numbers to left side and odd numbers to right side of Array:
int[] arr = {7, 2, 9, 8, 4, 1, 2, 6, 5};
Program to find the index difference between smallest and largest elements:
int[] arr = {5, 7, 3, 8, 6, 9, 4};
Program to print leader elements in the array : All elements to its right must be smaller to
Leader element
int arr[] = {10, 9, 14, 23, 15, 0, 9};
Transpose of matrix:
int[][] array = {{7, 5, 2},{5, 4, 8},{9, 2, 6}};
Strings
What is Character?
Character is any symbol represent with single quotes (alphabets, digits, symbols);
Example: A-Z , a-z, 0-9, $, #, @, !, ^, &, ......
Program to display First and Last characters of each string in the array:
String[] arr = {"java", "asp", "servlets", "ado.net", "springBoot"};
Program to count number of words in the given string without split() method
String s = "This is simple english sentense";
}
}
class Test
{
public static void fun(){
print("Hello all");
}
}
}
}
class Test
{
public void fun(){
print("Hello all");
}
}
}
}
class First{
public static void fun(){
print("First fun");
}
}
class Second{
public static void fun(){
print("Second fun");
}
}
}
}
class First{
public void fun(){
print("First fun");
}
}
class Second{
public void fun(){
print("Second fun");
}
}
}
}
class Add{
public static void nums(int a, int b)
{
}
}
}
}
class Multiply{
public void nums(int a, int b){
}
}
}
}
class Check{
public void isEven(int n){
}
}
}
}
class Person{
public static void canVote(int age){
}
}
}
}
class Check{
public static void isAlphabet(char ch){
}
}
}
}
class Check{
public void isAlphaNumeric(char ch){
}
}
}
}
class Find{
public void big(int a, int b, int c){
}
}
}
}
class Person{
public void canDonateBlood(char gender, int age, int weight){
}
}
}
}
class Check{
public void isPrime(int n){
}
}
}
}
class Print{
public static void table(int n){
}
}
}
}
class Add{
public static int nums(int a, int b)
// add and return value
}
}
}
}
class Check{
public String isEven(int n)
// return even or not message
}
}
if(valid)
print("Can vote");
else
print("Cannot vote");
}
}
class Person{
public boolean canVote(int age)
// return true or false
}
}
}
}
class Find{
public int big(int a, int b, int c){
// return biggest num
}
}
}
}
class Display{
public void empDetails(int id, String name, double salary){
}
}
}
}
class Display{
public void studDetails(String name, String course, double fee){
}
}
}
Write setters and Getters:
class Student
{
private String name, course;
private double fee;
}
}
class First
{
private static int a=10;
// define static getter
}
}
class First
{
private static int a;
// define static set and get methods
}
}
class First
{
private int a;
// define getter
}
}
class First
{
private int a;
// define set and get methods
// display values
}
}
class Emp
{
private int num;
private String name;
private double salary;
}
Invoke variables and print values:
public class Code{
public static void main(){
// Read student details
// display values
}
}
class Student
{
private String name, course;
private double fee;
}
}
class First
{
private int a;
public First( )
{
}
}
}
}
class First
{
private int a, b;
public First( )
{
}
}
}
}
class Employee
{
private int id;
private String name;
private double salary;
public Employee( )
{
}
public void printdDetails()
{
}
}
}
//Override toString() method
Establish inheritance relation and access the method by creating child object:
class Parent {
public void m1() {
print("Method m1() in Parent class");
}
}
class Child
{
public void m2() {
print("Method m2() in Child class");
}
}
public class Main {
public static void main() {
}
}
}
}
class Child
{
int c, d;
Child(int a, int b, int c, int d)
{
void details()
{
// print values
}
}
class Code
{
public static void main()
{
Child obj = new Child(10, 20, 30, 40);
obj.details();
}
}
}
class Main
{
public static void main() {
}
}
}
class Main {
public static void main(){
}
}
Collections Framework
Create an ArrayList object that stores integer objects.
Employee class:
• Create Employee class with instance variables id, name, salary
• Define parameterized constructor to initialize the object.
class Employee
{
int id;
String name;
double salary;
// Create Arguments constructor
Main class:
• Create 3 Employee objects and add to List
• Display details using for-each loop
import java.util.*;
class Main
{
public static void main()
{
// Create ArrayList that takes Employee objects
}
}
Employee class
• Create Employee class with instance variables id, name, salary
• Define parameterized constructor to initialize the object.
class Employee
{
int id;
String name;
double salary;
Employee(int id, String name, double salary) {
this.id = id;
this.name = name;
this.salary = salary;
}
}
Main class
• Collect values from Arrays to create Employee objects.
• Display details using for-each loop
import java.util.*;
class Main
{
public static void main() {
int[] ids = {101, 102, 103, 104, 105};
String[] names = {"Amar", "Annie", "Harini", "Satya", "Jai"};
double[] salaries = {23000, 56000, 43000, 48000, 16000};
// print list
}
}
Main class: Create List with 5 Employee details by reading through Scanner.
class Main
{
public static void main()
{
// Create List that takes Employee objects
// Read 5 employee details using for-loop, create objects and add inside loop
}
}
Main. class: Read and Add employee details until end user quits using while loop.
Employee class:
public class Employee
{
private int id;
private String name;
private double salary;
// define getters and setters
Main class: Read employee details and add using while loop
import java.util.*;
class Main
{
public static void main( ) {
}
}
Employee.class:
class Employee {
private int id;
private String name;
private double salary;
private int dept;
private String location;
int getId(){
return this.id;
}
String getName(){
return this.name;
}
double getSalary(){
return this.salary;
}
int getDept(){
return this.dept;
}
String getLocation(){
return this.location;
}
void setId(int id){
this.id = id;
}
void setName(String name){
this.name = name;
}
void setSalary(double salary){
this.salary = salary;
}
void setDept(int dept){
this.dept = dept;
}
void setLocation(String location){
this.location = location;
}
}
Main.java:
import java.util.*;
class Main {
public static void main(String[] args) {
int[] ids = {101, 102, 103, 104, 105, 106};
String[] names = {"Amar", "Hareen", "Sathya", "Annie", "Raji", "Harsha"};
double[] salaries = {30000, 35000, 40000, 45000, 42000, 50000};
int[] depts = {20, 10, 20, 20, 30, 10};
String[] locations = {"Hyderabad", "Chennai", "Bangalore", "Hyderabad", "Pune",
"Bangalore"};
}
}
Count how many employees working in both Hyderabad and Bangalore locations:
Display details whose salary below 40000 and not belongs to Hyderabad:
JDK 8 Features
Printing all elements of an ArrayList:
ArrayList<String> list = new ArrayList<>(Arrays.asList("apple", "banana", "cherry"));
list.forEach(System.out::println);
Convert a list of strings to uppercase and filter those starting with 'B':
List<String> list = Arrays.asList("apple", "banana", "grape", "kiwi");
List<String> result = list.stream().map(String::toUpperCase).filter(x ->
x.startsWith("B")).collect(Collectors.toList());
System.out.println(String.join(", ", result));