Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
512 views

Java - Practice Book

Uploaded by

Aashutosh Raj
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
512 views

Java - Practice Book

Uploaded by

Aashutosh Raj
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 170

Practice Book

Complete the Book


To Crack Every Interview

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

When was the first version of Java released?


a) 1990 b) 1995 c) 2000 d) 2005

Java is primarily known for its:


a) High performance b) Platform independence
c) Low-level memory manipulation d) Static typing

Java is known for its principle of:


a) Code once, run anywhere b) Code readability counts
c) Keep it simple, stupid d) Do one thing and do it well

Java is a _________ language.


a) Compiled b) Interpreted
c) Both compiled and interpreted d) None of the above

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 extension of Java source files?


a) .class b) .java c) .jar d) .jv

Which of the following is not a Java IDE (Integrated Development Environment)?


a) Eclipse b) NetBeans c) IntelliJ IDEA d) Visual Studio Code

Java programs are typically compiled into:


a) Machine code b) Bytecode c) Assembly code d) Source code

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 is based on which programming paradigm?


a) Procedural b) Functional c) Object-oriented d) Logical

Which of the following statements about Java syntax is true?


a) Java is case-insensitive. b) Java statements must end with a semicolon (;).
c) Java allows spaces in variable names. d) Java uses curly braces {} to define blocks of code.

Which of the following is not a valid comment in Java?


a) // This is a comment b) # This is a comment
c) /* This is a comment / d) /* This is a comment */

Contact : 911 955 6789


1
Ameerpet Technologies
Java Practice Book

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 use of variable?

How to declare variable?

How to assign value to a variable?

How to modify the value of variable?

What is variable initialization?

Write the rules to create variables?

Contact : 911 955 6789


2
Ameerpet Technologies
Java Practice Book

What is a variable in Java?


a) A special word in Java b) A temporary storage for data
c) A type of loop in Java d) A way to display output

Which of the following is a valid variable name in Java?


a) 2variable b) _variable c) variable@ d) variable-name

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

Which symbol is used for assignment in Java?


a) = b) == c) := d) ->

Which characters are allowed in a Java variable name?


a) Letters, digits, and underscores b) Spaces and special characters
c) Only uppercase letters d) Only digits and underscores

Which of the following is a valid class name in Java?


a) MyClass b) 123Class c) class d) my class

Can a Java variable start with a number?


a) Yes b) No

Are Java variable names case-sensitive?


a) Yes b) No

What is the purpose of using camelCase in Java variable names?


a) To separate words with underscores b) To make variable names more readable
c) To avoid using any capital letters d) To indicate that it is a constant variable

Can Java keywords be used as variable names?


a) Yes b) No

Which naming convention is recommended for class names in Java?


a) camelCase b) PascalCase c) snake_case d) kebab-case

Is it allowed to use spaces in variable names in Java?


a) Yes b) No

Can a Java variable have the same name as a keyword?


a) Yes b) No

Contact : 911 955 6789


3
Ameerpet Technologies
Java Practice Book

Basic Programs to Understand Variables Behavior


Display Message on Console:
public class Code
{
public static void main(String[] args)
{
System.out.println("Welcome to Java");
}
}

Variables must be without quotes while using them in programming:


public class Code
{
public static void main(String[] args)
{
int a=10;
System.out.println("a");
System.out.println('a');
System.out.println(a);
}
}

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);
}
}

Local variables cannot be accessed without initialization(assigning any value):


public class Code
{
public static void main(String[] args) {
int a;
System.out.println(a);
}
}

Contact : 911 955 6789


4
Ameerpet Technologies
Java Practice Book

Variable value can be modified with any operation:


public class Code {
public static void main(String[] args) {
int a=10;
a=20;
a=30;
System.out.println(a);
}
}

public class Code {


public static void main(String[] args) {
int a=5;
a=a+2;
a=a+3;
a=a+4;
System.out.println(a);
}
}

Printing Quotient and Remainder:


public class Code
{
public static void main(String[] args) {
int a=5, b=2;
System.out.println(a);
System.out.println(b);
}
}

Declaring different types of variables:


public class Code
{
public static void main(String[] args) {
String name = "Amar";
int age = 21;
System.out.println(name);
System.out.println(age);
}
}

Contact : 911 955 6789


5
Ameerpet Technologies
Java Practice Book

Arithmetic Operators

int a=10; a int a=5; a


a=20; a=a+1;
a=30; a=a+1;
a=40; a=a+1;
a=50; a=a+1;
print(a); print(a);
int a=5; a int a=15; a
a=a+1; a=a+5;
a=a+2; a=a+4;
a=a+3; a=a+3;
a=a+4; a=a+4;
print(a); print(a);
int a=5, x=1; a int a=5, b=5; a
a=a+x; a=a+b;
x = x+1; b = b-1;
a=a+x; a=a+b;
x = x+1; x b= b-1; b
a=a+x; a=a+b;
x = x+1; b = b-1;
a=a+x; a=a+b;
print(a, x); print(a, b);

int n=2; n s int n=2; n c


int s=n*n; int c=n*n*n;
print(s); print(c);

int n=2; s c int bal=5000; bal amt


int s=n*n; int amt=3500;
int c=n*n*n; bal = bal + amt;
print(s+c); print(bal);

int a=5, b=3; a b c int a=5, b=3; a b


int c=a+b; a=b;
print(c); b=a;
print(a,b);

int a=5, b=3, c; a b c int a=2, b=3; a b


c=a; a=a+b;
a=b; b=a+a;
b=c; print(a,b);
print(a,b);

Contact : 911 955 6789


6
Ameerpet Technologies
Java Practice Book

int a=2, b=3; a b int a=2, b=3; a b


a=a+b; a=a*b;
b=a-b; b=a/b;
a=a-b; a=a/b;
print(a,b); print(a,b);

int n=234; n d int n=234; n d


int d=n%10; int d=n/10;
print(d); print(d);

int sum=0, i=1; i sum int fact=1, i=1; i fact


sum=sum+i; fact=fact*i;
i=i+1; i=i+1;
sum=sum+i; fact=fact*i;
i=i+1; i=i+1;
sum=sum+i; fact=fact*i;
i=i+1; i=i+1;
sum=sum+i; fact=fact*i;
print(sum); print(fact);

int n=2345, sum=0; int n=2345, rev=0;


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;

sum=sum+n%10; rev=rev*10+n%10;
n=n/10; n=n/10;

print(sum, n); Print(rev, n);

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)

Contact : 911 955 6789


7
Ameerpet Technologies
Java Practice Book

Write Conditions using Arithmetic & Relational Operators

1. Condition for Number is Positive:


Variables Condition Testing
Valid case Invalid case
n=13 n=-5
int n = ? n >= 0 13>=0 -5>=0
true false

2. Condition for Number is Negative:

3. Condition for Numer is not zero:

4. Condition for 2 nums equal:

5. Condition for 2 nums not equal:

6. Condition for first num greater than second num:

7. Condition for sum of 2 numbers equals to 10

8. Condition for first 2 nums multiplication equals to third num

9. Condition for average of 4 nums greater than 60

10. Condition for the num is divisible by 7

11. Condition for the num is not divisible by 100

12. Condition for the num is Even

Contact : 911 955 6789


8
Ameerpet Technologies
Java Practice Book

13. Condition for the quantity of fruits exactly in dozens

14. Condition for sqare of first num equals to cube of the second num

15. Condition for the last digit of num is 5

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:

20. Condition for Person can Vote:

21. Condition for the last digit of given Number divisible by 3

22. Condition for the sum of First 2 numbers equals to last digit of 3rd num

23. Condition for average of 3 numbers equals to first number

24. Condition for the square of last digit is greater than 10

25. Condition for square of last digit of given number divisible by 3

Contact : 911 955 6789


9
Ameerpet Technologies
Java Practice Book

Programs on Arithemtic Operators

1. Program to add 2 numbers

2. Program to display quotient and remainder after division

3. Program to find the total and average of 3 numbers

4. Program to find the square of the given number

5. Program to find the cube of the given number

6. Program to find the sum of square and cube of given number.

Contact : 911 955 6789


10
Ameerpet Technologies
Java Practice Book

7. Program to display last digit of given number

8. Program to remove last digit of given number

9. Program to find the sum of first N numbers

10. Program to swap 2 numbers

11. Program to swap 2 numbers without 3rd variable

12. Program to calculate the total amount for the given quantity of fruits purchased

Contact : 911 955 6789


11
Ameerpet Technologies
Java Practice Book

13. Program to Find the Total salary for the given basic salary

14. Program to calculate Area of Circle

15. Program to calculate Area of Traiangle

16. Program to calculate time taken using speed and distance:

17. Program to calculate speed using distance and time:

18. Program to calculate distance using speed and time:

Contact : 911 955 6789


12
Ameerpet Technologies
Java Practice Book

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

public class Main{


public static void main(String[] args) {
int a=10;
System.out.println(a);
}
}
Output: 10

public class Main{


public static void main(String[] args) {
int a=10;
System.out.println("a");
}
}
Output: a

public class Main{


public static void main(String[] args) {
int a=10;

}
}
Output: A value = 10

Contact : 911 955 6789


13
Ameerpet Technologies
Java Practice Book

public class Main{


public static void main(String[] args)
{
int a=10, b=20;
System.out.println(a);

}
}
Output: 10
20

public class Main


{
public static void main(String[] args) {
int a=10, b=20;
System.out.println("a val : " + a);

}
}
Output: a val : 10
b val : 20

public class Main


{
public static void main(String[] args)
{
int a=10, b=20;

}
}
Output : 10, 20

public class Main{


public static void main(String[] args)
{
int a=10, b=20;

}
}
Output: 10 20

Contact : 911 955 6789


14
Ameerpet Technologies
Java Practice Book

public class Main


{
public static void main(String[] args) {
int a=10, b=20;
System.out.println(
}
}
Output: 10
20

public class Main


{
public static void main(String[] args)
{
int a=10, b=20;
System.out.println(
}
}
Output: a=10, b=20

public class Main{


public static void main(String[] args)
{
int a=10, b=20;
System.out.println(
}
}
Output: a=10
b=20

public class Main{


public static void main(String[] args)
{
int num=101;
String name="Amar";
double salary=35000;
System.out.println(
}
}
Output: 101, Amar, 35000.0

Contact : 911 955 6789


15
Ameerpet Technologies
Java Practice Book

public class Main{


public static void main(String[] args) {
int num=101;
String name="Amar";
double salary=35000;
System.out.println(
}
}
Output: Details : 101, Amar, 35000

public class Main{


public static void main(String[] args) {
int a=10, b=20;
int c=a+b;
System.out.println(
}
}
Output: Sum=30

public class Main{


public static void main(String[] args)
{
int a=10, b=20;
int c=a+b;
System.out.println("Sum of " + a + " and " + b + " is " + c);
}
}
Output: Sum of 10 and 20 is 30

public class Main{


public static void main(String[] args)
{
int a=10, b=20;
int c=a+b;
System.out.println(
}
}
Output: 10 + 20 = 30

Contact : 911 955 6789


16
Ameerpet Technologies
Java Practice Book

public class Main{


public static void main(String[] args) {
int a=10, b=20;
System.out.println(
}
}
Output: 10 + 20 = 30

public class Main{


public static void main(String[] args)
{
int a=5, b=2;
System.out.println(a + " + " + b + " = " + (a+b));

}
}
Output: 5 + 2 = 7
5–2=3
5 * 2 = 10
5/2=2
5%2=1

public class Main{


public static void main(String[] args) {
System.out.println("
}
}
Output: This is 'Java' class

public class Main


{
public static void main(String[] args) {
System.out.println("
}
}
Output: This is "Java" class

Contact : 911 955 6789


17
Ameerpet Technologies
Java Practice Book

public class Main


{
public static void main(String[] args) {
String course = "Java";
System.out.println("
}
}
Output: I am learning 'Java'

public class Main{


public static void main(String[] args)
{
String course = "Java";
System.out.println(
}
}
Output: I am learning "Java"

public class Main{


public static void main(String[] args)
{
int id=101;
String name="Amar";
double salary=23000;
System.out.println(
}
}
Output: Details = (101, Amar, 23000)

public class Main{


public static void main(String[] args)
{
int id=101;
String name="Amar";
double salary=23000;
System.out.println(
}
}
Output: Details = (101, 'Amar', 23000)

Contact : 911 955 6789


18
Ameerpet Technologies
Java Practice Book

Write the Conditions using Logical Operators

1. Condition for the number divisible by both 2 and 3?

2. Condition for the number divisible by 4 but not by 6?

3. Condition for the first number less than the second number and greater than the third number?

4. Condition for the number between 20 and 40?

5. Condition for the first number is even and the second number is odd?

6. Condition for the student score above 35 in all 4 subjects?

7. Condition for the character a vowel (a, e, i, o, u)?

8. Condition for the character an uppercase letter?

9. Condition for the character a digit (0-9)?

10. Condition for the PIN 4 digit long?

11. Condition for the character an alphabet letter?

12. Condition for the character a symbol (non-alphanumeric)?

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?

Contact : 911 955 6789


19
Ameerpet Technologies
Java Practice Book

Scanner Class – Reading Input from User

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

Contact : 911 955 6789


20
Ameerpet Technologies
Java Practice Book

Read 2 Nums & Perform Arithmetic Operations:


import java.util.Scanner;
public class Code
{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter two integers : ");
int a = scan.nextInt();
int b = scan.nextInt();
System.out.println(a + " + " + b + " = " + (a+b));
System.out.println(a + " - " + b + " = " + (a-b));
System.out.println(a + " * " + b + " = " + (a*b));
System.out.println(a + " / " + b + " = " + (a/b));
System.out.println(a + " % " + b + " = " + (a%b));
}
}

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);
}
}

Contact : 911 955 6789


21
Ameerpet Technologies
Java Practice Book

Output: Enter character : A


Input character is : A

Read Employee details and print:


import java.util.Scanner;
class Code
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter Emp details : ");
int id = scan.nextInt();
String name = scan.next();
double salary = scan.nextDouble();
System.out.println("Details : " + id + ", " + name + ", " + salary);
}
}
Output : Enter Emp details :
101
Amar
53000
Details : 101, Amar, 53000.0

Print Last Digit of given Number:


import java.util.Scanner;
public class Code
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter a number : ");
int n = scan.nextInt();
int d = n%10;
System.out.println("Last digit of " + n + " is " + d);
}
}
Output:
Enter a number :
234
Last digit of 234 is 4

Contact : 911 955 6789


22
Ameerpet Technologies
Java Practice Book

If Block Programs
If Block: Execute a block only if the specified condition is valid.
Syntax Flow Chart

if(Condition)
{
If-block-logic;
}

Display bill amount of customer:


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();
System.out.println("Pay : " + bill);
}
}

Give 15% bill amount to every customer:


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();
double discount = 0.15 * bill;
bill = bill-discount;
System.out.println("Pay : " + bill);
}
}

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;
}

Contact : 911 955 6789


23
Ameerpet Technologies
Java Practice Book

System.out.println("Pay : " + bill);


}
}

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.

Contact : 911 955 6789


24
Ameerpet Technologies
Java Practice Book

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.

Contact : 911 955 6789


25
Ameerpet Technologies
Java Practice Book

If Else Block Programs

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;
}

Program to check the input number is Positive or Negative:


import java.util.Scanner;
class Code
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter an integer : ");
int n = scan.nextInt();
if(n>=0)
System.out.println("Positive number");
else
System.out.println("Negative number");
}
}

Check the input number is Even or Odd:


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();

Contact : 911 955 6789


26
Ameerpet Technologies
Java Practice Book

if(
System.out.println("Even number");
else

}
}

Program to Check Person can Vote or Not:


import java.util.Scanner;
class Code
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter age : ");
int age =
if(
System.out.println("Eligible for Vote");
else
System.out.println("Wait " + (18-age) + " more years to vote");
}
}

Program to find the biggest of two numbers:


import java.util.Scanner;
class Code
{
public static void main(String[] args)
{

System.out.println("Enter 2 numbers : ");


int a =
int b =
if(a>b)
System.out.println("a is big");
else
System.out.println("b is big");
}
}

Contact : 911 955 6789


27
Ameerpet Technologies
Java Practice Book

Program to check the character is Vowel or Not


import java.util.Scanner;
class Code
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter character : ");
char ch =
if(
System.out.println("Vowel");
else
System.out.println("Not vowel");
}
}

Program to check the character is Alphabet or Not:


import java.util.Scanner;
class Code
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter character : ");
char ch = scan.next().charAt(0);
if(
System.out.println("Alphabet");
else
System.out.println("Not an Alphabet");
}
}

Program to Check Login details are Correct or Not:


import java.util.Scanner;
class Code
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter user name : ");
String user =

Contact : 911 955 6789


28
Ameerpet Technologies
Java Practice Book

System.out.println("Enter password : ");


int pwd =
if(user.equals("logic") && pwd==1234)
System.out.println("Login Success");
else
System.out.println("Error : Invalid login");
}
}

Program to Check the Number between 30 and 50 or not:


import java.util.Scanner;
class Code
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter number between 30 and 50 : ");
int num = scan.nextInt();
if(
System.out.println("Valid number entered");
else
System.out.println("Invalid number entered");
}
}

Check the input year is Leap year or Not:


import java.util.Scanner;
class Code{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter year : ");
int n = scan.nextInt();
if(
System.out.println("Leap year");
else
System.out.println("Not a leap year");
}
}

Contact : 911 955 6789


29
Ameerpet Technologies
Java Practice Book

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;
}

Check the Number is Positive or Negative or Zero

class Code
{
public static void main(String[] args)
{

System.out.println("Enter n value : ");


int n =
if(n>0)
System.out.println("Positive num");
else if(n<0)
System.out.println("Negative num");
else
System.out.println("Zero");
}
}

Check the Character is Alphabet or Digit or Symbol


import java.util.Scanner;
class Code
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);

Contact : 911 955 6789


30
Ameerpet Technologies
Java Practice Book

System.out.println("Enter character : ");


char ch =
if(
System.out.println("Alphabet");
else if(
System.out.println("Digit");
else
System.out.println("Special Symbol");
}
}

Program to check the input year is Leap or Not:


Leap Year rules:
• 400 multiples are leap years : 400, 800, 1200, 1600….
• 4 multiples are leap years: 4, 8, 12, … 92, 96…
• 100 multiples are not leap years: 100, 200, 300, 500, 600…
import java.util.Scanner;
class Code
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter year : ");
int n = scan.nextInt();
if((n%400==0))
System.out.println("Leap year");
else if(
System.out.println("Leap Year");
else
System.out.println("Not leap year");
}
}

Program to find Biggest of Three Numbers:


import java.util.Scanner;
class Code
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter a, b, c values : ");
int a = scan.nextInt();
int b = scan.nextInt();
int c = scan.nextInt();
if(
System.out.println("a is big");
else if(

Contact : 911 955 6789


31
Ameerpet Technologies
Java Practice Book

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

Program to Calculate current bill based on units consumed:


• 0-100 -> 0.80 per unit
• 101-200 -> 1.2 per unit
• 201-300 -> 1.5 per unit
• above 300 -> 1.8 per unit

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 if(units>200 && units<=300)

else

System.out.println("Total bill amount : " + bill);


}
}

Output: Enter number of units: 150


Total bill amount : 140.0

Contact : 911 955 6789


32
Ameerpet Technologies
Java Practice Book

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

Contact : 911 955 6789


33
Ameerpet Technologies
Java Practice Book

Biggest of two only if the two numbers or not equal


import java.util.Scanner;
class Code
{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter a, b values : ");
int a = scan.nextInt();
int b = scan.nextInt();
if( ){
if( )
System.out.println("a is big");
else
System.out.println("b is big");
}
else{
System.out.println("a and b are equal");
}
}
}
Output: Enter a, b values : 10
20
b is big

Program to check the person can donate blood or not


Requirements: Age between 18 to 60 and Weight must be greater than 50
import java.util.Scanner;
class Code
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter age : ");
int age = scan.nextInt();
System.out.println("Enter weight : ");
int weight = scan.nextInt();
if(
{
if(
System.out.println("Can donate blood");
else
System.out.println("Under weight");
}
else
System.out.println("Not suitable age");
}
}

Contact : 911 955 6789


34
Ameerpet Technologies
Java Practice Book

Output: Enter age : 25


Enter weight : 49
Under weight

Display Student Grade only if the student passed in all Subjects


import java.util.Scanner;
class Code
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter marks of 3 subjects : ");
int m1 = scan.nextInt();
int m2 = scan.nextInt();
int m3 = scan.nextInt();
if(
{
int avg =
if(
System.out.println("Grade-A");
else if(
System.out.println("Grade-B");
else
System.out.println("Grade-C");
}
else{
System.out.println("Student failed");
}
}
}
Output: Enter marks of 3 subjects:
45
56
67
Grade-B

Check the Triangle is Equilateral or Isosceles or Scalene


• Equilateral: All sides are equal a==b==c
• Isosceles: Any two sides are equal a==b or a==c or b==c
• Scalene: No sides are equal a != b != c
import java.util.Scanner;
class Code
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter 3 sides of triangle : ");

Contact : 911 955 6789


35
Ameerpet Technologies
Java Practice Book

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

Display days for the specified month


import java.util.Scanner;
class Code
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter Month number : ");
int n = scan.nextInt();
if(
{
if(n==2)
System.out.println("28 days / 29 days");
else if(
System.out.println("30 days");
else
System.out.println("31 days");
}
else{
System.out.println("Invalid month number");
}
}
}
Output: Enter Month number : 2
28 days / 29 days

Contact : 911 955 6789


36
Ameerpet Technologies
Java Practice Book

Introduction to Loops

Loop: A Block of instructions execute repeatedly as long the condition is valid.

Note: Block executes only once whereas Loop executes until condition become False

Java Supports 3 types of Loops:


1. For Loop
2. While Loop
3. Do-While Loop

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.

Contact : 911 955 6789


37
Ameerpet Technologies
Java Practice Book

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

for(init ; condition ; modify)


{
statements;
}

for(start ; stop ; step)


{
statements;
}

Program to Print 1 to 10 Numbers


class Code {
public static void main(String[] args) {
for (int i=1 ; i<=10 ; i++)
{
System.out.println("i val : " + i);
}
}
}

Program to Print 10 to 1 numbers


class Code{
public static void main(String[] args) {
for (int i=10 ; i>=1 ; i--)
{
System.out.println("i val : " + i);
}
}
}

Program to display A-Z alphabets


class Code {
public static void main(String[] args) {
for (char ch='A' ; ch<='Z' ; ch++)
{
System.out.print(ch + " ");
}
}
}

Contact : 911 955 6789


38
Ameerpet Technologies
Java Practice Book

Print numbers 2, 4, 6, 8, 10

Print numbers 15, 12, 9, 6, 3, 0

Print numbers 10, 20, 30, 40, 50

Print numbers 100, 80, 60, 40, 20

Print lower case alphabets a to z

Print Upper case alphabets in reverse order Z to A

Contact : 911 955 6789


39
Ameerpet Technologies
Java Practice Book

Write the outputs for the following:

Program to Print 1 to N numbers

Program to Print N to 1 numbers:

Contact : 911 955 6789


40
Ameerpet Technologies
Java Practice Book

Program to print ASCII Values from A-Z

Program to print ASCII values from a-z

Program to print ASCII values of 0-9

Program to display ASCII character set

Contact : 911 955 6789


41
Ameerpet Technologies
Java Practice Book

Program to print square values for numbers 1 to 5

Program to print cube values for numbers 1 to 5

Find Sum of First N numbers

Program to Find Factorial of Number

Contact : 911 955 6789


42
Ameerpet Technologies
Java Practice Book

Program to print the numbers divisible by 7 between 20 and 60

Program to print numbers divisible by 3 and not divisible by 5 between 10 to 50

Program to print numbers divisible by 4 and not divisible by 100 from 100 to 300

Program to print numbers which are not divisible by 5 from 30 to 70

Program to print even numbers from 1 to 30 which are not divisible by 5

Contact : 911 955 6789


43
Ameerpet Technologies
Java Practice Book

Program to display Multiplication table

Print Even Numbers from 1 to 10

Find Sum of Even Numbers in Java

Program to count factors of given number

Contact : 911 955 6789


44
Ameerpet Technologies
Java Practice Book

Program to print factors of given number

Program to count factors of given number

Program to find the sum of factors of given number

Contact : 911 955 6789


45
Ameerpet Technologies
Java Practice Book

Program to check the input number is Prime or Not

Program to check the input number is Perfect or Not

Program to print Fibonacci series

Contact : 911 955 6789


46
Ameerpet Technologies
Java Practice Book

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.

Syntax Flow Chart

while(condition)
{
statements;
}

Check even or Not until user exits:


import java.util.Scanner;
public class Check
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
while(true)
{
System.out.print("Enter a number : ");
int num = scan.nextInt();

if(num%2==0)
System.out.println(num + " is even.");
else
System.out.println(num + " is odd.");

System.out.print("Do you want to check another number? (y/n): ");


char ch = scan.next().charAt(0);
if(ch=='n')
break;
}
System.out.println("Exiting program.");
}
}

Read 2 numbers and add them until user exits:

Contact : 911 955 6789


47
Ameerpet Technologies
Java Practice Book

Print Multiplication table until user exits:

Contact : 911 955 6789


48
Ameerpet Technologies
Java Practice Book

Check the Number is Prime or Not until user exits:

Menu driven program to perform arithmetic operations:


import java.util.Scanner;
public class Code
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
while(true)
{
System.out.println("1. add");
System.out.println("2. subtract");
System.out.println("3. multiply");
System.out.println("4. divide");

Contact : 911 955 6789


49
Ameerpet Technologies
Java Practice Book

System.out.println("5. exit");

System.out.print("Enter your choice : ");


int ch = scan.nextInt();
if(ch==1)
{
System.out.println("Enter 2 nums : ");
int a = scan.nextInt();
int b = scan.nextInt();
System.out.println("Result = " + (a+b));
}
else if(ch==2)
{
System.out.println("Enter 2 nums : ");
int a = scan.nextInt();
int b = scan.nextInt();
System.out.println("Result = " + (a-b));
}
else if(ch==3)
{
System.out.println("Enter 2 nums : ");
int a = scan.nextInt();
int b = scan.nextInt();
System.out.println("Result = " + (a*b));
}
else if(ch==4)
{
System.out.println("Enter 2 nums : ");
int a = scan.nextInt();
int b = scan.nextInt();
System.out.println("Result = " + (a/b));
}
else if(ch==5)
{
System.out.println("End of program");
break;
}
else
System.out.println("Error : Invalid choice");
}
}
}

Contact : 911 955 6789


50
Ameerpet Technologies
Java Practice Book

Digit Based Programs


Program to Display the Last digit of given number:
int n = 321875;

Program to Remove the Last digit of given number:


int n = 321875;

Program to Display all digits one by one in reverse order:


int n = 321875;

Program to count the digits in given number:


int n = 321875;

Contact : 911 955 6789


51
Ameerpet Technologies
Java Practice Book

Program to find the sum of digits in given number:


int n = 321875;

Program to check last digit is even or not:


int n = 321875;

Program to display only even digits in the given number:


int n = 321875;

Program to find the sum of even digits in the given number:


int n = 321875;

Contact : 911 955 6789


52
Ameerpet Technologies
Java Practice Book

Program to count even digits in the given number:


int n = 321875;

Program to find the largest digit in the given number:


int n = 321875;

Program to find the smallest digit in the given number:


int n = 321875;

Contact : 911 955 6789


53
Ameerpet Technologies
Java Practice Book

Program to check the number contains zero or not:


int n = 321875;

Program to find the average of all digits in the given number:


int n = 321875;

Program to find the second largest digit in the given number:


int n = 321875;

Contact : 911 955 6789


54
Ameerpet Technologies
Java Practice Book

Program to find the second smallest digit in the given number:


int n = 321875;

Program to find the first digit in the given number:


int n = 321875;

Program to find the sum of first and last digits in the given number:
int n = 321875;

Contact : 911 955 6789


55
Ameerpet Technologies
Java Practice Book

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;

Contact : 911 955 6789


56
Ameerpet Technologies
Java Practice Book

Program to display only prime digits in the given number:


int n = 321875;

Program to reverse the given number


class Code
{
public static void main(String[] args)
{
int n = 321875;
int rev=0, r;
while(n>0)
{
r = n%10;
rev = rev*10 + r;
n = n/10;
}
System.out.println("Reverse Number is : " + rev);
}
}

Contact : 911 955 6789


57
Ameerpet Technologies
Java Practice Book

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

Contact : 911 955 6789


58
Ameerpet Technologies
Java Practice Book

Program to find the square root value for the given number without library method:
int n = 144 → ans = 12

Check the given 3 digit number is Armstrong Number or not :


Sum of cubes of individual digits equals to the same number
Example: 153 -> 1^3 + 5^3 + 3^3 = 153

Program to check the given number is Armstrong number or not:


Armstrong Number: Sum of its own digits raised to power number of digits
Examples : 153 = 1^3 + 5^3 + 3^3 = 153
1634 = 1^4 + 6^4 + 3^4 + 4^4 = 1634

Contact : 911 955 6789


59
Ameerpet Technologies
Java Practice Book

Program to find Sum of Digits till Single Digit:


9657 -> 9+6+5+7 -> 27 -> 2+7 -> 9

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;

Contact : 911 955 6789


60
Ameerpet Technologies
Java Practice Book

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");
}
}

Contact : 911 955 6789


61
Ameerpet Technologies
Java Practice Book

Break and Continue

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

Break statement terminates the flow of infinite loop also:


class Code
{
public static void main(String[] args) {
while(true){
System.out.print("Loop");
break;
}
}
}

Output: Loop prints infinite times

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

Contact : 911 955 6789


62
Ameerpet Technologies
Java Practice Book

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");
}
}
}

Output: Enter character(r, g, b): g


Green

Contact : 911 955 6789


63
Ameerpet Technologies
Java Practice Book

Arithmetic Operations using Menu options:


import java.util.Scanner;
class Code
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("1.Add");
System.out.println("2.Subtract");
System.out.println("3.Multiply");
System.out.println("4.Divide");

System.out.print("Enter your choice : ");


int ch = sc.nextInt();

int a=0, b=0;


if(ch>=1 && ch<=3)
{
System.out.println("Enter 2 nums : ");
a = sc.nextInt();
b = sc.nextInt();
}
switch(ch)
{
case 1 : System.out.println("Sum : " + (a+b));
break;

case 2 : System.out.println("Difference : " + (a-b));


break;

case 3 : System.out.println("Product : " + (a*b));


break;

case 4 : System.out.println("Quotient : " + (a/b));


break;

default: System.out.println("Invalid choice");


}
}
}
Output : 1. Add
2. Subtract
3. Multiply
Enter your choice : 2
30
10
Difference : 20

Contact : 911 955 6789


64
Ameerpet Technologies
Java Practice Book

Do-While Loop
do-while: Executes a block at least once and continue iteration until condition is false.

Syntax Flow Chart

do
{
statements;
} while(condition);

Check Even numbers until user exits:


import java.util.Scanner;
class Code
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
char res='n';
do
{
System.out.print("Enter num : ");
int n = sc.nextInt();
if(n%2==0)
System.out.println(n + " is even");
else
System.out.println(n + " is not even");

System.out.print("Do you want to check another num (y/n) : ");


res = sc.next().charAt(0);

}while (res == 'y');


}
}

Output: Enter num : 5


5 is not even
Do you want to check another num (y/n) : y
Enter num : 6
6 is even
Do you want to check another num (y/n) : n

Contact : 911 955 6789


65
Ameerpet Technologies
Java Practice Book

Nested For Loop


Nested for loop: Defining for loop inside another for loop. We used nested loops to process two-
dimensional data such as patterns, matrix type arrays, range based programs, sorting, remove duplicates
in arrays, display duplicate count of each element in array and so on.

Syntax Flow chart

for(init1 ; cond1 ; modify1)


{
for(init2 ; cond2 ; modify2)
{
Statements;
}
}

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);
}
}

Output : Number of Iterations : 25

Contact : 911 955 6789


66
Ameerpet Technologies
Java Practice Book

Range Based Programs


Program to display even numbers from 1 to 20

Program to print factorial for numbers 2 to 7

Program to display multiplication tables in the given range

Contact : 911 955 6789


67
Ameerpet Technologies
Java Practice Book

Program to display Prime numbers in the given range

Program to display Perfect numbers in the given range

Contact : 911 955 6789


68
Ameerpet Technologies
Java Practice Book

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.

Basic Number Patterns


Pattern Logic
for (int i=1 ; i<=5 ; i++)
{
12345
for (int j=1 ; j<=5 ; j++)
12345
12345 {
12345 System.out.print(j);
}
System.out.println();
}

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();
}

Contact : 911 955 6789


69
Ameerpet Technologies
Java Practice Book

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();
}

Contact : 911 955 6789


70
Ameerpet Technologies
Java Practice Book

Basic Character Patterns


Pattern Logic
for(char x='A' ; x<='E'; x++){
AAAAA for(char y='A' ; y<='E' ; y++){
BBBBB
CCCCC
DDDDD }
EEEEE System.out.println();
}
Pattern Logic
ABCDE for(char x='A' ; x<='E'; x++){
ABCDE for(char y='A' ; y<='E' ; y++){
ABCDE
ABCDE
ABCDE }
System.out.println();
}
Pattern Logic
for(char x='E' ; x>='A'; x--){
EEEEE for(char y='E' ; y>='A' ; y--){
DDDDD
CCCCC
BBBBB }
AAAAA System.out.println();
}
Pattern Logic
for(char x='E' ; x>='A'; x--){
EDCBA for(char y='E' ; y>='A' ; y--){
EDCBA
EDCBA
EDCBA }
EDCBA System.out.println();
}

Basic Patterns with Conditions


Pattern Logic
for (int i=1 ; i<=5 ; i++){
for (int j=1 ; j<=5 ; j++){
$$$$$
if(
#####
$$$$$ System.out.print("#");
##### else
$$$$$ System.out.print("$");
}
System.out.println();
}

Contact : 911 955 6789


71
Ameerpet Technologies
Java Practice Book

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();
}

Contact : 911 955 6789


72
Ameerpet Technologies
Java Practice Book

Patterns Plus Cross Swastika


Pattern Logic
+++++++ for (int i=1 ; i<=7 ; i++)
+++++++ {
+++++++
for (int j=1 ; j<=7 ; j++)
+++++++
+++++++ {
+++++++ 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”);
}

Contact : 911 955 6789


73
Ameerpet Technologies
Java Practice Book

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”);
}

Contact : 911 955 6789


74
Ameerpet Technologies
Java Practice Book

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”);
}

Contact : 911 955 6789


75
Ameerpet Technologies
Java Practice Book

Contact : 911 955 6789


76
Ameerpet Technologies
Java Practice Book

Patterns – All Digits


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<=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”);
}

Contact : 911 955 6789


77
Ameerpet Technologies
Java Practice Book

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”);
}

Contact : 911 955 6789


78
Ameerpet Technologies
Java Practice Book

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”);
}

Contact : 911 955 6789


79
Ameerpet Technologies
Java Practice Book

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”);
}

Contact : 911 955 6789


80
Ameerpet Technologies
Java Practice Book

Numbers Triangle Patterns


Pattern Logic

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

Contact : 911 955 6789


81
Ameerpet Technologies
Java Practice Book

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

Contact : 911 955 6789


82
Ameerpet Technologies
Java Practice Book

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

Contact : 911 955 6789


83
Ameerpet Technologies
Java Practice Book

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

Contact : 911 955 6789


84
Ameerpet Technologies
Java Practice Book

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

Contact : 911 955 6789


85
Ameerpet Technologies
Java Practice Book

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

Contact : 911 955 6789


86
Ameerpet Technologies
Java Practice Book

Star Triangle Patterns


Pattern Logic
for (int i=1 ; i<=5 ; i++){
* for (int j=1 ; j<=i ; j++){
** Printf(“*”);
*** }
**** Printf(“\n”);
***** }

Pattern Logic

*****
****
***
**
*
Pattern Logic

*
**
***
****
*****

Pattern Logic

*****
****
***
**
*

Pattern Logic

*
**
***
****
*****
****
***
**
*

Contact : 911 955 6789


87
Ameerpet Technologies
Java Practice Book

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”);
}
}

*****
****
***
**
*
**
***
****
*****

*****
****
***
**
*
**
***
****
*****

Contact : 911 955 6789


88
Ameerpet Technologies
Java Practice Book

Binary Number Patterns


Pattern Logic
int k=1;
for (int i=1 ; i<=5 ; i++){
1
for (int j=1; j<=i ; j++){
01
010 Printf(k++%2);
1010 }
10101 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

Contact : 911 955 6789


89
Ameerpet Technologies
Java Practice Book

Border Only Patterns

Pattern Logic

*
**
* *
* *
* *
* *
* *
********

Pattern Logic

********
* *
* *
* *
* *
* *
**
*

Pattern Logic

********
* *
* *
* *
* *
* *
**
*

Contact : 911 955 6789


90
Ameerpet Technologies
Java Practice Book

Pattern Logic

*
**
* *
* *
* *
* *
* *
********

Pyramid Patterns
Pattern Logic

*
***
*****
*******
*********

Pattern Logic

*
* *
* *
* *
*********

Contact : 911 955 6789


91
Ameerpet Technologies
Java Practice Book

Pattern Logic
1
222
33333
4444444
555555555

Reverse Pyramid Patterns


Pattern Logic

*********
*******
*****
***
*

Pattern Logic

*********
* *
* *
* *
*

Contact : 911 955 6789


92
Ameerpet Technologies
Java Practice Book

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

Contact : 911 955 6789


93
Ameerpet Technologies
Java Practice Book

Pattern Logic
1
121
12321
1234321
123454321

Pattern Logic

123454321
1234321
12321
121
1

Pattern Logic

1
212
32123
4321234
543212345

Contact : 911 955 6789


94
Ameerpet Technologies
Java Practice Book

Arrays
Declare Array Variable

Initialize integer array with 5 values

Create Empty Integer Array with size 5

Display length of following array:


Int[] arr = {3, 7, 8, 2, 5, 6, 4};

Display First element of array:


Int[] arr = {3, 7, 8, 2, 5, 6, 4};

Display last element of array:


Int[] arr = {3, 7, 8, 2, 5, 6, 4};

Display Sum of First and Last elements of Array:


Int[] arr = {3, 7, 8, 2, 5, 6, 4};

Contact : 911 955 6789


95
Ameerpet Technologies
Java Practice Book

Check the first element of array is even or not:


Int[] arr = {3, 7, 8, 2, 5, 6, 4};

Print Multiplication table for last element in the array:


Int[] arr = {3, 7, 8, 2, 5, 6, 4};

Display the middle element of following array of odd length:


Int[] arr = {3, 7, 8, 2, 5, 6, 4};

Display sum of 2 middle elements in the given even array of elements:


Int[] arr = {3, 7, 8, 2, 9, 5, 6, 4};

Contact : 911 955 6789


96
Ameerpet Technologies
Java Practice Book

Display all elements in the array:


Int[] arr = {3, 7, 8, 2, 5, 6, 4};

Display array elements in reverse order:


Int[] arr = {3, 7, 8, 2, 5, 6, 4};

Find the sum of array elements:


Int[] arr = {3, 7, 8, 2, 5, 6, 4};

Display only even numbers in the given array:


Int[] arr = {3, 7, 8, 2, 5, 6, 4};

Contact : 911 955 6789


97
Ameerpet Technologies
Java Practice Book

Count odd numbers in the given array:


Int[] arr = {3, 7, 8, 2, 5, 6, 4};

Display Sum of Even elements in the given array:


Int[] arr = {3, 7, 8, 2, 5, 6, 4};

Display elements using for-each loop:


Int[] arr = {3, 7, 8, 2, 5, 6, 4};

Display sum of elements using for-each loop:


Int[] arr = {3, 7, 8, 2, 5, 6, 4};

Contact : 911 955 6789


98
Ameerpet Technologies
Java Practice Book

Display even elements in array using for-each loop:


Int[] arr = {3, 7, 8, 2, 5, 6, 4};

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};

Contact : 911 955 6789


99
Ameerpet Technologies
Java Practice Book

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 elements in specified locations of array:


Int[] arr = {3, 7, 8, 2, 5, 6, 4};
Int x = 2, y = 3;

Swap array element with its adjecnt element for the specified location:
Int[] arr = {3, 7, 8, 2, 5, 6, 4};
Int loc = 3;

Contact : 911 955 6789


100
Ameerpet Technologies
Java Practice Book

Display Largest element in the array:


Int[] arr = {3, 7, 8, 2, 5, 6, 4};

Display smallest element in the array:


Int[] arr = {3, 7, 8, 2, 5, 6, 4};

Display First even number in the array:


Int[] arr = {3, 7, 8, 2, 5, 6, 4};

Contact : 911 955 6789


101
Ameerpet Technologies
Java Practice Book

Display last odd element in the array:


Int[] arr = {3, 7, 8, 2, 5, 6, 4};

Swap Smallest and Largest elements in the array:


Int[] arr = {3, 7, 8, 2, 5, 6, 4};

Swap First even and Last Odd elements in the array:


Int[] arr = {3, 7, 8, 2, 5, 6, 4};

Contact : 911 955 6789


102
Ameerpet Technologies
Java Practice Book

Display Second biggest element in the array:


Int[] arr = {3, 7, 8, 2, 5, 6, 4};

Display Second smallest element in the array:


Int[] arr = {3, 7, 8, 2, 5, 6, 4};

Contact : 911 955 6789


103
Ameerpet Technologies
Java Practice Book

Copy elements from one array to another array.


Int[] src = {3, 7, 8, 2, 5, 6, 4};

Create new array with only even numbers of given array:


Int[] arr = {3, 7, 8, 2, 5, 6, 4};

Create new array with only odd numbers of given array:


Int[] arr = {3, 7, 8, 2, 5, 6, 4};

Contact : 911 955 6789


104
Ameerpet Technologies
Java Practice Book

Create 2 new arrays with even and odd numbers from the given mixed elements array:
Int[] arr = {3, 7, 8, 2, 5, 6, 4};

Check the element is duplicated or not in the given array:


Int[] arr = {3, 7, 8, 2, 5, 6, 4};

Contact : 911 955 6789


105
Ameerpet Technologies
Java Practice Book

Linear Search Algorithm:


Int[] arr = {3, 7, 8, 2, 5, 6, 4};
Int ele = 5;

Binary Search algorithm:


Int[] arr = {3, 7, 8, 2, 5, 6, 4};
Int ele = 5;

Contact : 911 955 6789


106
Ameerpet Technologies
Java Practice Book

Sort all elements in the 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};

Contact : 911 955 6789


107
Ameerpet Technologies
Java Practice Book

Merge 2 arrays:
Int[] a1 = {3, 7, 8, 2,};
Int[] a2 = {5, 6, 4};

Read the Size and Create Array:

Create the array by reading size and fill the array with elements by reading again from user:

Contact : 911 955 6789


108
Ameerpet Technologies
Java Practice Book

Program to display the pair of elements whose sum equals to 10


Int[] arr = {3, 7, 8, 2, 5, 6, 4};

Program to replace all duplicates with 0:


int[] arr = {6, 2, 3, 1, 6, 7, 6, 3, 6, 2, 3, 2, 1};

Contact : 911 955 6789


109
Ameerpet Technologies
Java Practice Book

Program to display pair of elements whose sum is 10 (contains duplicates in array):


int[] arr = {6, 3, 9, 1, 2, 8, 4, 5, 7, 6, 2, 9, 1, 4};

Program to find the common elements from 2 arrays.


int[] a1 = {1, 2, 5, 5, 8, 9, 5, 7, 10};
int[] a2 = {3, 6, 15, 6, 5, 4, 7, 2, 1};

Contact : 911 955 6789


110
Ameerpet Technologies
Java Practice Book

Program to find the duplicates in the array


int[] arr = {1, 2, 5, 5, 8, 9, 2, 5, 7, 1, 10, 1, 2};

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};

Contact : 911 955 6789


111
Ameerpet Technologies
Java Practice Book

Program to check 2 arrays are equal or not:


int[] a1 = {3, 4, 5, 6, 7};
int[] a2 = {3, 4, 5, 6, 7};

Program to find the missing number in the given array.


int[] arr = {2, 3, 4, 5, 7, 8, 9};

Contact : 911 955 6789


112
Ameerpet Technologies
Java Practice Book

Program to find the largest difference of Array elements:


int[] arr = {5, 7, 3, 8, 6, 9, 4};

Program to find the index difference between smallest and largest elements:
int[] arr = {5, 7, 3, 8, 6, 9, 4};

Contact : 911 955 6789


113
Ameerpet Technologies
Java Practice Book

Program to check array contains only positive numbers or not


int[] arr = {5, 7, 3, 8, 6, -4, 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};

Contact : 911 955 6789


114
Ameerpet Technologies
Java Practice Book

Two Dimensional Array Programs


Define 3x3 dimensional array with elements:

Display elemnts of 3x3 dimensional array:


int[][] array = {{7, 5, 2},{5, 4, 8},{9, 2, 6}};

Display smallest element in 3x3 dimensional array:


int[][] array = {{7, 5, 2},{5, 4, 8},{9, 2, 6}};

Display largest element in 3x3 dimensional array:


int[][] array = {{7, 5, 2},{5, 4, 8},{9, 2, 6}};

Contact : 911 955 6789


115
Ameerpet Technologies
Java Practice Book

Display sum of all elements in the given array:


int[][] array = {{7, 5, 2},{5, 4, 8},{9, 2, 6}};

Display sum of each row in the given matrix


int[][] array = {{7, 5, 2},{5, 4, 8},{9, 2, 6}};

Display sum of each column in the given matrix


int[][] array = {{7, 5, 2},{5, 4, 8},{9, 2, 6}};

Contact : 911 955 6789


116
Ameerpet Technologies
Java Practice Book

Display Max row sum in the given matrix:


int[][] array = {{7, 5, 2},{5, 4, 8},{9, 2, 6}};

Transpose of matrix:
int[][] array = {{7, 5, 2},{5, 4, 8},{9, 2, 6}};

Contact : 911 955 6789


117
Ameerpet Technologies
Java Practice Book

Matrix addition program:

Matrix Multiplication Program:

Contact : 911 955 6789


118
Ameerpet Technologies
Java Practice Book

Strings

What is Character?
Character is any symbol represent with single quotes (alphabets, digits, symbols);
Example: A-Z , a-z, 0-9, $, #, @, !, ^, &, ......

ASCII value table


A-65 a-97 0-48 #-35
B-66 b-98 1-49 $-36
... .... .. ...
... .... .. ...
... .... .. ...
Z-90 z-122 9-57 ...

Can we assign character to integer variable?


We can directly assign character to integer called “Implicit Cast”. The ASCII value will store into
integer variable.

Auto conversion Manually casting


char ch='a'; char ch='a';
int x=ch; int x=(int)ch;
print(x); print(x);

How to convert integer into character?


We cannot assign integer value directly to character variable. We must explicitly cast.

Direct assignment : Error Manually casting


int x=100; int x=100;
char ch=x; char ch=(char)x;
print(ch); //Error print(ch); //d

Converting Upper case to lower case character as follows:


char ch='M';
ch = (char)(ch+32);
print(ch);

Converting Lower case to Upper case character as follows:


char ch='a';
ch = (char)(ch-32);
print(ch);

Convert Character to Digit:


char ch='5';
int x=ch-48;
print(x); // 5

Contact : 911 955 6789


119
Ameerpet Technologies
Java Practice Book

Program to Check the character is vowel or not:

program to check the given character is digit or not:

Program to check the character is upper case alphabet or not

program to check the character is Alphabet or not

Program to check the character is special symbol or not

Contact : 911 955 6789


120
Ameerpet Technologies
Java Practice Book

Program to display ASCII value of given character

Program to convert upper case character to lower case character

Display the length of given character array


char[] arr = {'a' , 'x' , '3' , 'm', 'x', '@' , 'p', '7', 'm', '4', '$'};

Display First character of character array:


char[] arr = {'a' , 'x' , '3' , 'm', 'x', '@' , 'p', '7', 'm', '4', '$'};

Check the First character is Alphabet or Not:


char[] arr = {'a' , 'x' , '3' , 'm', 'x', '@' , 'p', '7', 'm', '4', '$'};

Display all characters in the array:


char[] arr = {'a' , 'x' , '3' , 'm', 'x', '@' , 'p', '7', 'm', '4', '$'};

Contact : 911 955 6789


121
Ameerpet Technologies
Java Practice Book

Display in reverse order:


char[] arr = {'a' , 'x' , '3' , 'm', 'x', '@' , 'p', '7', 'm', '4', '$'};

Display only alphabets in the array:


char[] arr = {'a' , 'x' , '3' , 'm', 'x', '@' , 'p', '7', 'm', '4', '$'};

Count alphabets, digits and symbols in the array:


char[] arr = {'a' , 'x' , '3' , 'm', 'x', '@' , 'p', '7', 'm', '4', '$'};

Display Sum of Digits:


char[] arr = {'a' , 'x' , '3' , 'm', 'x', '@' , 'p', '7', 'm', '4', '$'};

Contact : 911 955 6789


122
Ameerpet Technologies
Java Practice Book

Display array using for each:


char[] arr = {'a' , 'x' , '3' , 'm', 'x', '@' , 'p', '7', 'm', '4', '$'};

Program to display length of String:


String s = "Coding";

Program to display First and Last characters of String:


String s = "Coding";

Program to print String character by character:


String s = "Coding";

Program to print the String in reverse order:


String s = "Coding";

Program to check the 2 strings equal or not:


String s1="Coding";
String s2="Code";

Contact : 911 955 6789


123
Ameerpet Technologies
Java Practice Book

Program to create reverse string from given string:


String s = "Coding";
String rev="";

Program to count Alphabets, Digits and Symbols in the given String


String s = "Coding@365";

Check String is Palindrome or Not:


String line = "racecar";

Contact : 911 955 6789


124
Ameerpet Technologies
Java Practice Book

Program to find the sum of digits in the given String:


String s = "Coding@365";

Display the ASCII values of characters in the given String:


String s = "Coding";

Program to convert upper case string to lower case string:


String s = "CoDiNg@365";
String res="";

Contact : 911 955 6789


125
Ameerpet Technologies
Java Practice Book

Program to display highest digit in the given String:


String s = "coding@365";

Program to find the length of String array


String[] arr = {"java", "asp", "servlets", "ado.net", "springBoot"};

Program to display Strings from Array:


String[] arr = {"java", "asp", "servlets", "ado.net", "springBoot"};

Program to display the length of each String in the array:


String[] arr = {"java", "asp", "servlets", "ado.net", "springBoot"};

Program to display First and Last characters of each string in the array:
String[] arr = {"java", "asp", "servlets", "ado.net", "springBoot"};

Contact : 911 955 6789


126
Ameerpet Technologies
Java Practice Book

Program to display String array in reverse order:


String[] arr = {"java", "asp", "servlets", "ado.net", "springBoot"};

Program to display each String in reverse order from Array:


String[] arr = {"java", "asp", "servlets", "ado.net", "springBoot"};

Program to Split the String into Words:


String s = "This is simple english sentense";

Program to count number of words in the given string without split() method
String s = "This is simple english sentense";

Contact : 911 955 6789


127
Ameerpet Technologies
Java Practice Book

Program to check two strings are Anagrams or not:


We can say if two strings are an anagram of each other if they contain the same characters but at
different orders. For example, army & mary
String s1 = "army";
String s2 = "mary";

Program to display longest word in the given String:


String s = "This is the Longest Sentense in English";

Contact : 911 955 6789


128
Ameerpet Technologies
Java Practice Book

Program to remove duplicates in the String:


String str = "aaabbababaacccbabdcccbdddbac";
String res = "";

Program to remove spaces in String:


String s = "This is a String";

Program to remove multiple spaces in the given string:


String s = "This is a String";

Contact : 911 955 6789


129
Ameerpet Technologies
Java Practice Book

Program to print characters specified by the number of times:


Input: abc3e2f4
Expected output: abccceeffff

Program to swap the side-by-side characters in the given string:


String s1 = "abcde";
String s2 = "";

Contact : 911 955 6789


130
Ameerpet Technologies
Java Practice Book

Program to display the charaacter count in the given string:


Input : aaabbbaccccddacdd
Output : a-5, b-3, c-5, d-4

Contact : 911 955 6789


131
Ameerpet Technologies
Java Practice Book

Object oriented Programming


Complete the Code Programs – By defining logics and invoking methods

Invoke the Method and Complete the Logic:


public class Code{
public static void main(){

}
}
class Test
{
public static void fun(){
print("Hello all");
}
}

Invoke the Method and Complete the Logic:


public class Code{
public static void main(){

}
}
class Test
{
public void fun(){
print("Hello all");
}
}

Invoke the Method and Complete the Logic:


public class Code{
public static void main(){

}
}
class First{
public static void fun(){
print("First fun");
}
}
class Second{
public static void fun(){
print("Second fun");
}
}

Contact : 911 955 6789


132
Ameerpet Technologies
Java Practice Book

Invoke the Method and Complete the Logic:


public class Code{
public static void main(){

}
}
class First{
public void fun(){
print("First fun");
}
}
class Second{
public void fun(){
print("Second fun");
}
}

Invoke the Method and Complete the Logic:


public class Code{
public static void main(){

}
}
class Add{
public static void nums(int a, int b)
{

}
}

Invoke the Method and Complete the Logic:


public class Code{
public static void main(){

}
}
class Multiply{
public void nums(int a, int b){

}
}

Contact : 911 955 6789


133
Ameerpet Technologies
Java Practice Book

Invoke the Method and Complete the Logic:


public class Code{
public static void main(){
// Read input and invoke method

}
}
class Check{
public void isEven(int n){

}
}

Invoke the Method and Complete the Logic:


public class Code{
public static void main(){
// Read input and invoke method

}
}
class Person{
public static void canVote(int age){

}
}

Invoke the Method and Complete the Logic:


public class Code{
public static void main(){
// Read input and invoke method

}
}

Contact : 911 955 6789


134
Ameerpet Technologies
Java Practice Book

class Check{
public static void isAlphabet(char ch){

}
}

Invoke the Method and Complete the Logic:


public class Code{
public static void main(){
// Read input and invoke method

}
}
class Check{
public void isAlphaNumeric(char ch){

}
}

Invoke the Method and Complete the Logic:


public class Code{
public static void main(){
// Read input and invoke method

}
}
class Find{
public void big(int a, int b, int c){

Contact : 911 955 6789


135
Ameerpet Technologies
Java Practice Book

}
}

Invoke the Method and Complete the Logic:


public class Code{
public static void main(){
// Read input and invoke method

}
}
class Person{
public void canDonateBlood(char gender, int age, int weight){

}
}

Contact : 911 955 6789


136
Ameerpet Technologies
Java Practice Book

Invoke the Method and Complete the Logic:


public class Code{
public static void main(){
// Read input and invoke method

}
}
class Check{
public void isPrime(int n){

}
}

Invoke the Method and Complete the Logic:


public class Code{
public static void main(){
// Read input and invoke method

}
}
class Print{
public static void table(int n){

}
}

Contact : 911 955 6789


137
Ameerpet Technologies
Java Practice Book

Invoke the Method and Complete the Logic:


public class Code{
public static void main(){
// invoke the method

}
}
class Add{
public static int nums(int a, int b)
// add and return value

}
}

Invoke the Method and Complete the Logic:


public class Code{
public static void main(){
// invoke the method

}
}
class Check{
public String isEven(int n)
// return even or not message

}
}

Invoke the Method and Complete the Logic:


public class Code{
public static void main(){
// invoke the method

Contact : 911 955 6789


138
Ameerpet Technologies
Java Practice Book

if(valid)
print("Can vote");
else
print("Cannot vote");
}
}
class Person{
public boolean canVote(int age)
// return true or false

}
}

Invoke the Method and Complete the Logic:


public class Code{
public static void main(){
// invoke the method

}
}
class Find{
public int big(int a, int b, int c){
// return biggest num

}
}

Contact : 911 955 6789


139
Ameerpet Technologies
Java Practice Book

Invoke the Method and Complete the Logic:


public class Code{
public static void main(){
// Read details and invoke

}
}
class Display{
public void empDetails(int id, String name, double salary){

}
}

Invoke the Method and Complete the Logic:


public class Code{
public static void main(){
// Read details and invoke

}
}
class Display{
public void studDetails(String name, String course, double fee){

}
}

Contact : 911 955 6789


140
Ameerpet Technologies
Java Practice Book

Write Setters and Getters:


class Code
{
private int a;

Write Setters and Getters:


class Code
{
private int a, b;

Write setters and Getters:


class Emp
{
private int id;
private String name;
private double salary;

Contact : 911 955 6789


141
Ameerpet Technologies
Java Practice Book

}
Write setters and Getters:
class Student
{
private String name, course;
private double fee;

Contact : 911 955 6789


142
Ameerpet Technologies
Java Practice Book

Invoke variables and print values:


public class Code{
public static void main(){
// invoke and display

}
}
class First
{
private static int a=10;
// define static getter

Invoke variables and print values:


public class Code{
public static void main(){
// set value a=10 and print

}
}
class First
{
private static int a;
// define static set and get methods

Contact : 911 955 6789


143
Ameerpet Technologies
Java Practice Book

Invoke variables and print values:


public class Code{
public static void main(){
// invoke and display

}
}
class First
{
private int a;
// define getter

Invoke variables and print values:


public class Code{
public static void main(){
// set value a=10 and print

}
}
class First
{
private int a;
// define set and get methods

Contact : 911 955 6789


144
Ameerpet Technologies
Java Practice Book

Invoke variables and print values:


public class Code{
public static void main(){
// Read emp details

// create object and set values

// display values

}
}
class Emp
{
private int num;
private String name;
private double salary;

Contact : 911 955 6789


145
Ameerpet Technologies
Java Practice Book

}
Invoke variables and print values:
public class Code{
public static void main(){
// Read student details

// create object and set values

// display values

}
}

Contact : 911 955 6789


146
Ameerpet Technologies
Java Practice Book

class Student
{
private String name, course;
private double fee;

Contact : 911 955 6789


147
Ameerpet Technologies
Java Practice Book

Invoke variables and print values:


public class Code{
public static void main(){
// create object by passing a value

}
}
class First
{
private int a;
public First( )
{

}
}

Invoke variables and print values:


public class Code{
public static void main(){
// create object by passing a, b values

}
}
class First
{
private int a, b;
public First( )
{

}
}

Invoke variables and print values:


public class Code{
public static void main(){
// create object and print details

}
}

Contact : 911 955 6789


148
Ameerpet Technologies
Java Practice Book

class Employee
{
private int id;
private String name;
private double salary;
public Employee( )
{

}
public void printdDetails()
{

}
}

Override the toString() method to display employee details


class Employee
{
private int id;
private String name;
private double salary;
public Employee( )
{

}
//Override toString() method

Contact : 911 955 6789


149
Ameerpet Technologies
Java Practice Book

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() {

}
}

Initialize instance varaibles – complete the code:


class Parent
{
int a, b;
Parent(int a, int b)
{

}
}
class Child
{
int c, d;
Child(int a, int b, int c, int d)
{

Contact : 911 955 6789


150
Ameerpet Technologies
Java Practice Book

void details()
{
// print values

}
}
class Code
{
public static void main()
{
Child obj = new Child(10, 20, 30, 40);
obj.details();
}
}

Complete the code by overriding abstract method and invoke methods:


abstract class Parent
{
public void m1(){
println("Parent class concrete m1()");
}
public abstract void m2();
}
class Child
{

}
class Main
{
public static void main() {

}
}

Contact : 911 955 6789


151
Ameerpet Technologies
Java Practice Book

Complete the interface implementation invoke:


interface First {
void m1();
void m2();
}
class Second
{

}
class Main {
public static void main(){

}
}

Contact : 911 955 6789


152
Ameerpet Technologies
Java Practice Book

Collections Framework
Create an ArrayList object that stores integer objects.

Create an ArrayList object that stores Employee objects.

How do you add elements to an ArrayList in JAVA?

How do you find the number of elements present in an ArrayList?

How do you check if an ArrayList is empty in JAVA?

How do you display elements at a specified index number in an ArrayList?

How do you insert an element into a specified index in an ArrayList?

How do you remove all elements in an ArrayList?

How do you remove a specified index element in an ArrayList?

Contact : 911 955 6789


153
Ameerpet Technologies
Java Practice Book

How do you check whether an element exists in an ArrayList?

How do you replace an existing value in an ArrayList?

How do you display an ArrayList using a for-each loop in JAVA?

How do you display an ArrayList in reverse order in JAVA?

How do you display elements using an Iterator in JAVA?

How do you display elements using a ListIterator in JAVA?

How do you display elements in reverse order using a ListIterator in JAVA?

How do you merge two ArrayLists in JAVA?

How to you sort elements in the ArrayList in JAVA?

Contact : 911 955 6789


154
Ameerpet Technologies
Java Practice Book

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

// Create 3 Employee objects by calling parameterized constructor

// add objects to list

// Display details using for-each

}
}

Contact : 911 955 6789


155
Ameerpet Technologies
Java Practice Book

Display using for loop:

Display Employees List in reverse order:


• We must use for() loop to iterate in reverse order.
• For-each loop can move only in forward direction.

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};

Contact : 911 955 6789


156
Ameerpet Technologies
Java Practice Book

// create ArrayList that takes Employee Object

// Create objects by taking values from array and add to ArrayList

// print list

}
}

Approach-3: (Read details using Scanner class)


Employee class
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: 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

Contact : 911 955 6789


157
Ameerpet Technologies
Java Practice Book

// print list using Iterator

}
}

Approach-4: (Store objects to list until user quits)


Employee class:
• Create Employee class with instance variables id, name, salary
• Define parameterized constructor to initialize the object.

Main. class: Read and Add employee details until end user quits using while loop.

Contact : 911 955 6789


158
Ameerpet Technologies
Java Practice Book

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( ) {

Contact : 911 955 6789


159
Ameerpet Technologies
Java Practice Book

// Display employee details

}
}

Contact : 911 955 6789


160
Ameerpet Technologies
Java Practice Book

Write code for following instructions:


• Define Employee with variables id, name, salary, dept, location.
• Create an ArrayList of Employee type and store following values from arrays.
Id Name Salary Dept Location
101 Amar 30000 20 Hyderabad
102 Hareen 35000 10 Chennai
103 Sathya 40000 20 Bangalore
104 Annie 45000 20 Hyderabad
105 Raji 42000 30 Pune
106 Harsha 50000 10 Bangalore

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;

Contact : 911 955 6789


161
Ameerpet Technologies
Java Practice Book

}
}

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"};

// create List and Add

// display details using for-each loop

}
}

Contact : 911 955 6789


162
Ameerpet Technologies
Java Practice Book

Display details using for loop:

Display details in reverse order:

Display Employee details whose ID is 103:

Display Employee details belongs to Hyderabad:

Contact : 911 955 6789


163
Ameerpet Technologies
Java Practice Book

Display Employee details belongs in department 20 or 30:

Display employee details those who not belongs to Hyderabad.

Contact : 911 955 6789


164
Ameerpet Technologies
Java Practice Book

Display details belongs to department 20 and not belongs to Hyderabad:

Count how many employees working in both Hyderabad and Bangalore locations:

Check the Employee with name “Amar” present or not:

Contact : 911 955 6789


165
Ameerpet Technologies
Java Practice Book

Display details whose salary greater than 35000:

Display details whose salary between 30000 and 40000:

Display details whose salary below 40000 and not belongs to Hyderabad:

Contact : 911 955 6789


166
Ameerpet Technologies
Java Practice Book

JDK 8 Features
Printing all elements of an ArrayList:
ArrayList<String> list = new ArrayList<>(Arrays.asList("apple", "banana", "cherry"));
list.forEach(System.out::println);

Double each element in a list:


List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
List<Integer> result = list.stream().map(x -> x * 2).collect(Collectors.toList());
System.out.println(result);

Filter even numbers in a list:


List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
List<Integer> result = list.stream().filter(x -> x % 2 == 0).collect(Collectors.toList());
System.out.println(result);

Convert list elements to uppercase strings:


List<String> list = Arrays.asList("apple", "banana", "cherry");
List<String> result = list.stream().map(String::toUpperCase).collect(Collectors.toList());
System.out.println(result);

Filter strings starting with 'A' in a list:


List<String> list = Arrays.asList("Apple", "Banana", "Orange", "Apricot");
List<String> result = list.stream().filter(x -> x.startsWith("A")).collect(Collectors.toList());
System.out.println(result);

Square each element in a list:


List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
List<Integer> result = list.stream().map(x -> x * x).collect(Collectors.toList());
System.out.println(result);

Filter prime numbers in a list:


List<Integer> list = Arrays.asList(2, 3, 4, 5, 6, 7, 8, 9, 10);
List<Integer> result = list.stream().filter(x -> isPrime(x)).collect(Collectors.toList());
System.out.println(result);

Double each element and then sum them in a list:


List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
int result = list.stream().mapToInt(x -> x * 2).sum();
System.out.println(result);

Contact : 911 955 6789


167
Ameerpet Technologies
Java Practice Book

Filter strings with length greater than 5 in a list:


List<String> list = Arrays.asList("apple", "banana", "orange", "grapefruit");
List<String> result = list.stream().filter(x -> x.length() > 5).collect(Collectors.toList());
System.out.println(result);

Join strings in a list:


List<String> list = Arrays.asList("apple", "banana", "cherry");
String result = String.join(", ", list);
System.out.println(result);

Count odd numbers in a list:


List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
long result = list.stream().filter(x -> x % 2 != 0).count();
System.out.println(result);

Find distinct even numbers in a list:


List<Integer> list = IntStream.rangeClosed(1, 10).boxed().collect(Collectors.toList());
List<Integer> result = list.stream().filter(x -> x % 2 == 0).distinct().collect(Collectors.toList());
System.out.println(String.join(", ", result));

Calculate the sum of squares of elements in a list:


List<Integer> list = IntStream.rangeClosed(1, 10).boxed().collect(Collectors.toList());
int result = list.stream().mapToInt(x -> x * x).sum();
System.out.println(result);

Find the longest string in a list:


List<String> list = Arrays.asList("apple", "banana", "grape", "kiwi");
String result = list.stream().max(Comparator.comparingInt(String::length)).orElse(null);
System.out.println(result);

Filter numbers greater than the average in a list:


List<Integer> list = IntStream.rangeClosed(1, 10).boxed().collect(Collectors.toList());
double avg = list.stream().mapToInt(Integer::intValue).average().orElse(0.0);
List<Integer> result = list.stream().filter(x -> x > avg).collect(Collectors.toList());
System.out.println(String.join(", ", result));

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));

Contact : 911 955 6789


168
Ameerpet Technologies
Java Practice Book

Check if all strings in a list contain the letter 'a':


List<String> list = Arrays.asList("apple", "banana", "grape", "kiwi");
boolean result = list.stream().allMatch(x -> x.contains("a"));
System.out.println(result);

Find the second largest element in a list:


List<Integer> list = Arrays.asList(10, 5, 20, 15, 30);
int result = list.stream().sorted(Comparator.reverseOrder()).skip(1).findFirst().orElse(0);
System.out.println(result);

Calculate the product of all elements in a list:


List<Integer> list = IntStream.rangeClosed(1, 5).boxed().collect(Collectors.toList());
int result = list.stream().reduce(1, (x, y) -> x * y);
System.out.println(result);

Check if any string in a list contains the letter 'z':


List<String> list = Arrays.asList("apple", "banana", "grape", "kiwi");
boolean result = list.stream().anyMatch(x -> x.contains("z"));
System.out.println(result);

Contact : 911 955 6789


169

You might also like