Java - A Complete Practical Solu - Swati Saxena
Java - A Complete Practical Solu - Swati Saxena
By
Swati Saxena
FIRST EDITION 2018
Copyright © BPB Publications, INDIA
ISBN :978-93-88176-50-7
Distributors:
BPB PUBLICATIONS
New Delhi-110002
Ph: 23254990/23254991
DECCAN AGENCIES
Ph: 24756967/24756400
Delhi-110006
Ph: 23861747
MICRO MEDIA
MUMBAI-400 001
Ph: 22078296/22078297
Published by Manish Jain for BPB Publications, 20, Ansari Road, Darya Ganj,
New Delhi-110002 and Printed by Repro India Pvt Ltd, Mumbai
Preface
This book helps you to understand each and every topic of java
practically.
It will help you in developing software and websites because one
should have sound practical knowledge.
It covers all the topics which are important from the point of view
of the interview, certification and examinations and no topic is left
untouched.
This is a complete practical book.
This book has been written after a long experience .
Despite the fact that ample care has been taken, the possibility of
minor inaccuracies cannot be ruled out.
So, if any, your suggestions are highly solicited.
Lastly, Thanks to all thestudents who believe in me.
Swati Saxena
Acknowledgement
History in Brief
Magic Code : Bytecode
Operators in java
Java Comment
Java Control Statement
Iteration / Looping
Array
Object and classes
Constructor
Static
“This”Keyword
Final Keyword
Java Regular Expressions (RegeX)
String
Instanceof
Inner Class
Inheritance
Super
Overriding
Abstraction
Abstract Class
Interface
Exception
The try-with- resource statement
Package
Collection and Generics
Applet
Life Cycle of Java Applet
AWT package
Adapter Class
Multhreading
Networking
File Handling ( IO package)
Serialization
Java Advance
Swing
JApplet
JDBC
Servlet
JSP
Extra Efforts
RMI , Border in Swing Component , LookAndFeel etc
Some Interview Question based on practical and Theory
HISTORY IN BRIEF:
Java Byte Code is the language to which Java source is compiled and
the Java Virtual Machine understands. Unlike compiled languages that
have to be specifically compiled for each different type of computers, a
Java program only needs to be converted to byte code once, after
which it can run on any platform for which a Java Virtual Machine
exists.
Bytecode is a set of instruction designed to be executed by the java
run time system, which is called JVM.
JVM is an interpreter of bytecode.
Features of Java:
✓ Simple
✓ Secure
✓ Platform Independent
✓ Object Oriented
✓ Robust
✓ Portable
✓ Dynamic
✓ Multithreaded
✓ Compiled and interpreted
both ✓ Supports networking
✓ High Performance
✓ Distributed
✓ Architecture Neutral
{
public static void main(String [] arg)
{
System.out.println(“Welcome to Swati Computers”);
}
}
Save it as : First.java
Compile: C:\>javac First.java (it will create a First.class file that
contains bytecode)
Run: c:\> java First
Keywords in java:
Data Types in Java:
Data types represent the different values to be stored in the variable. In
java, there are two types of data types:
o Primitive data types
o Non-primitive data types
Datatype
1. Primitive
A) Boolean
boolean
B) Numeric
Character
char
Integeral
Integer
byte
short
int
long
Floating point
float
double
2. Non primitive
A) String
B) Array
C) etc.
Types of Variable:
There are three types of variables in Java:
o local variable
o instance variable
o static variable
2. Write a Java program to interchange values of two variable
without using any third variable?
class Swap
{
public static void main(String [] arg)
{
int a=2,b=3;
a=a+b;
b=a-b;
a=a-b;
System.out.println(“A=”+a+”\nb=”+b);
}
}
3. Write a Java program to check whether main() function can
overload or not?
class Overload
{
public static void main(Integer [] aq)
{
System.out.println(“hi”);
}
public static void main(String [] ar)
{
System.out.println(“Hello”);
}
}
4. Write a program to input length and breadth of rectangle and
calculate the area ( Input through command line argument)?
class Rect_area
{
public static void main(String [] aa)
{
int length= Integer.parseInt(aa[0]);
int area=length*breath;
System.out.println(“the output is “+area);
}
}
5. Write a program to input total money and check how many of two
thousand, five hundred, hundred, fifty, twenty, ten, five rupee note
we need?
import java.util.*;
class notes
{
public static void main(String [] ar)
{
int thousand_2,hundred_5,hundred_1,fifty,ten,five,note;
note=sc.nextInt();
thousand_2=note/2000;
note=note%2000;
hundred_5=note/500;
note=note%500;
hundred_1=note/100;
note=note% 100;
fifty=note/50;
note=note%50;
ten=note/10;
note%=10;
five=note/5;
note=note%5;
System.out.println(“We need \n2000rs note:”+thousand_2+”\
n500rs note:”+hundred_5+”\n100rs note:”+hundred_1+”\n50rs
note:”+fifty+”\n10rs note:”+ten+”\n5 rs note:”+five+”\nextra:”+note);}
}
{
public static void main(String [] aa)
{
int principal= Integer.parseInt(aa[0]);
double rate=Double.parseDouble(aa[2]);
double si=(principal*time*rate)/100;
System.out.println(“the SI is “+si);
}
}
7. Write a program to input the name and age of a person and print
(input through Scanner class)?
import java.util.*;
class inp
{
public static void main(String [] ar)
{
Scanner sc; //reference variable
sc=new Scanner(System.in);//object
String name;
String lname;
int age,i,count=0;
System.out.println(“enter ur name”);
name=sc.next();
System.out.println(“enter last name”);
lname=sc.next();
System. out.println(“enter age”);
age=sc.nextInt();
System. out.println(“Age:”+age);
System. out.println(“Hello “+name);
int len=name.length()+lname.length();
System. out.println(len);
}
}
class Stu
{
String n,cou;
java.util.Scanner sc;
public void read()
{
sc=new java.util.Scanner(System.in);
System.out.println(“Enter name and course”);
n=sc.next();
cou=sc.next();
}
public void inp(String n,String course)
{
this.n=n;
cou=course;
}
public String name()
{
return n;
}
public void disp()
{
System.out.println(“Hello “+n+” u r doing “+cou);
}
}
class Stu_demo
{
public static void main(String [] sd)
{
Stu p=new Stu();
//p.read();
p.inp( "swati" , "java" ); p.disp();
System.out.println(“bye “+p.name());
}
}
{
public static void main(String [] arg) //throws IOException
{
int n;
try{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
System.out.println(“enter a no”);
n=Integer.parseInt(br.readLine());
System.out.println(“u input :”+n);
}
catch(IOException e)
{
System.out.println(“err”);
}
System.out.println(“byeee.”);
}
}
10. Write a program to input name and print length of name?
import java.util.*;
class inp
{
public static void main(String [] ar)
{
Scanner sc; //reference variable
sc=new Scanner(System.in);//object
String name;
String lname;
System.out.println(“enter ur name”);
name=sc.next();
System.out.println(“enter last name”);
lname=sc.next();
System. out.println(“Hello “+name);
int len=name.length()+lname.length();
System.out.println(len);
}
}
11. Write a program to input three numbers and print their addition
(using command line)?
class Nums
{
public static void main(String [] aa)
{
int sum=0;
int a= Integer.parseInt(aa[0]);
int b= Integer.parseInt(aa[1]);
int c= Integer.parseInt(aa[2]);
sum=a+b+c;
System.out.println(“the output is “+sum);
}
}
OPERATORS IN JAVA:
1. Arithmetic Operators: +, -, *, /, %
2. Unary Operators: ++, --
3. Assignment Operators : =
4. Relational Operators: <, >, <=, >=
5. Comparision operator: ==
6. Logical Operators : &&, ||, !
7. Ternary Operators : (condition )? True statement : false
statement
8. Bitwise Operators : &, |, ^
9. Shift Operators: << , >>, >>>
10. Compound asssignment: +=, - =, *=, /=, %=
{
public static void main(String args[])
{
int a=2;
int b=5;
int min=(a<b)?a:b;
System.out.println(min);
}
}
JAVA COMMENT:
1. If- else
Syntax:
if (expression1)
{
// codes
}
else if(expression2)
{
// codes
}
else if (expression3)
{
// codes
}
.
.
else
{
// codes
}
2. Switch case
Syntax:
switch (variable/expression)
{
case value1:
// statements break;
case value2:
// statements
break;
.. .. ...
.. .. ...
default:
// statements
}
13. Write a Java program to check whether two String variable are equal
or not?
{ class String_Demo
public static void main(String []
ar) {
String a,b=”hi”;
a=ar[0];
System.out.println(“address of a:”+a.hashCode());
System.out.println(“address of b:”+b.hashCode());
if(a==b)
System.out.println(“equal”);
else
System.out.println(“not equal”);
if(a.equals(b))
System.out.println(“equal”);
else
System.out.println(“not equal”);
String c=new String(“sub”);
String s=new String(b);
System.out.println(“address of c:”+c.hashCode());
System.out.println(“address of s:”+s.hashCode());
if(a==c)
System.out.println(“equal”);
else
System.out.println(“not equal”);
if(a.equals(c))
System. out.println(“equal”);
else
System. out.println(“not equal”);
}
}
14. Write a program to fin d out maximum out of three?
public class JavaExample
{
public static void main(String[] args)
{
int num1 = 10, num2 = 20, num3 = 7;
if( num1 >= num2 && num1 >= num3)
import java.util.Scanner;
class Calculator
{
public static void main (String[] args) {
char operator;
Double number1,nymber2,result;
Scanner scanner = new Scanner(System.in);
number1 = scanner.nextDouble();
number2 = scanner.nextDouble();
switch (operator) {
case ‘+’:
result = number1 + number2;
System.out.print(number1 + “+” + number2 + “ = “ + result);
break;
case ‘-’:
result = number1 - number2;
System.out.print(number1 + “-” + number2 + “ = “ + result);
break;
case ‘*’:
result = number1 * number2;
System.out.print(number1 + “*” + number2 + “ = “ + result);
break;
case '/':
result = number1 / number2;
System.out.print(number1 + “/” + number2 + “ = “ + result);
break;
default:
System.out.println(“Invalid operator!”);
break;
}
}
}
16. Write a program to check whether a given year is leap year or not?
import java.util.Scanner;
class Calculator
{
public static void main(String[] args)
{
int chk_year;
Scanner scanner = new Scanner(System.in);
System.out.println(“Enter year”);
Chk_year=scanner.nextInt();
if ((chk_year % 400) == 0)
System.out.println(“ year”+ chk_year+” is leap year”);
else if ((chk_year % 4) == 0)
else
System.out.println(chk_year + “ is not a leap year”);
}
}
class Ladder
{
public static void main(String[] args)
{
int number = 0;
if (number > 0)
{
System.out.println(“Number is positive.”);
}
else if (number < 0)
{
System.out.println(“Number is negative.”);
}
else
{
System.out.println(“Number is 0.”);
}
}
}
class Rates
{
public static void main(String[] args)
{
double PR,dis, amount;
Scanner scanner = new Scanner(System.in);
PR=scanner.nextDouble();
If(PR>=8000)
dis=PR* .10;
else if(PR>=5000)
dis=PR*.08;
else if(PR>=1000)
dis=PR*.04;
else
dis=100;
amount=PR-dis;
System.out.println(“Amount payable after “+ dis+” discount
is “+amount);
}
}
ITERATION/ LOOPING:
{
public static void main(String [] ar)
{
Scanner sc; //reference variable
String name;
Int i,count=0;
System.out.println(“enter ur name”);
name=sc.next();
System.out.println(“Hello “+name);
for(i=0;i<name.length();i++)
{
char c=name.charAt(i);
if(c== 'a' | |c== 'e' | |c== 'i' | |c== 'o' | |c== 'u' )
{
count++;
}
System. out.print(c+”:”);
}
System.out.println(“no. of vowels in “+name+” is “+count);
}
}
{
public static void main(String [] aa)
{
Scanner as= new Scanner(System.in);
String email;
int i,count=0,count1=0;
System.out.println(“ enter the email “);
email= as.next();
int c=email.length();
for(i=0;i<email.length();i++)
{ char k=email.charAt(i);
if(k==’@’)
{
count++;
}
if(k==’.’)
{
count1++;
}
}
if(count==1 &&count1 >0)
{
System.out.println(“valid id”);
}
else
{
System.out.println(“valid id ni h “);
}
}
}
class ReverseNumberWhile
{
public static void main(String args[])
{
int num=0;
int reversenum =0;
System.out.println(“Input your number and press enter: “);
num = in.nextInt();
//While Loop: Logic to find out the reverse number
while( num != 0 )
{
reversenum = reversenum * 10;
num = num/10;
}
System.out.println(“Reverse of input number is: “+reversenum);
}
}
if(n==1){
return 1;
}
//Recursion: Function calling itself!!
output = fact(n-1)* n;
return output;
}
}
class ReverseNumberWhile
{
public static void main(String args[])
{
int num=0;
int i=0,j=1;
System.out.println(“Input your number and press enter: “);
num = in.nextInt();
while(i<=num)
{
System.out.println(i);
j=i+j;
i=J-i;
}
}
}
{
public static void main(String args[])
{
int n;
int status = 1;
int num = 3;
//For capturing the value of n
Scanner scanner = new Scanner(System.in);
System.out.println(“Enter the value of n:”);
//The entered value is stored in the var n
n = scanner.nextInt();
if(n >= 1)
{
System.out.println(“First “+n+” prime numbers are:”);
//2 is a known prime number
System.out.println(2);
}
for ( int i = 2 ; i <=n ; )
{
for ( int j = 2 ; j <= Math.sqrt(num) ; j++ )
{
if ( num%j == 0 )
{
status = 0;
break;
}
}
if ( status != 0 )
{
System.out.println(num);
i++;
}
status = 1;
num++;
}
}
}
import java.util.*;
import java.io.*;
class Login
{
public static void main(String [] args)
{
String uname,pwd;
uname=sc.next();
//uname=con.readLine();
System.out.println(“Enter user password”);
//pwd=sc.next();
p=con.readPassword();
System.out.println(“Hello user :”+uname);
Array is an object that contain elements of the similar data type. We can
store only fixed set of elements in a Java array.
Once defined, the size of an array is fixed and cannot increase to
accommodate more elements.The first element of an array starts with
index zero.
Syntax:
Datatype[] arrname;
arrname=new datatype[size of array];
datatype [][] arrname=new datatype[rows][cols];
Advantages of array:
o Code Optimization: It makes the code optimized, we can retrieve or
sort the data easily.
o Random access: We can get any data located at any index position.
27. Write a program to input five numbers in an array and calculate their
sum and find maximum?
import java.util.*;
class arry1
{
public static void main(String []at)
{
Scanner sc=new Scanner(System.in);
int i,s=0,max=0;
for(i=0;i<5;i++)
{
System. out.println(“Enter no. ”);
a[i]=sc.nextInt();
s=s+a[i];
if(a[i]>max)
max=a[i];
}
for(i=0;i<5;i++)
{
System.out.println(“a[“ + i + “]=” + a[i]);
}
System.out.println(“Sum =”+s);
System. out.println(“Max=”+max);
}
}
class Arry3
{
public static void main(String []at)
{
Scanner sc=new Scanner(System.in);
class arry4
{
public static void main(String []at)
{
Scanner sc=new Scanner(System.in);
String [] col=new String[]{“red”,”green”,”blue”};
int i;
for(i=0;i<col.length;i++)
{
System.out.println(col[i]+” : “+col[i].length());
}
}
}
class sgn
{
public static void main(String [] aa)
{
Random r= new Random();
char [] q1=new char[] {'a','b','c','d','e','i' ,'g','h','i','j','k','l','m','n','o','
P' , 'q' , 'r' , 's' , 't' , 'u ', 'v' , 'w' , 'x' , 'y' , 'z' };
char [] q2=new char[] {‘A’,’ B’,’C ’,'D', E’ ,’F ’ ,’G ’ ,’H ’, 'I’,’J', ’K’,’L’,’
M','N','O’,'P’,'Q',’R’,'S','T','T','v','U’,'v’,'W’,'X’,'Y’,'Z’};
int f=r. nextInt(20);
System.out.print(q2[f ]);
System.out.print(f+100*f+q1[f ]);
System.out.print(q1[f/2]);
}
}
int i,j,k;
for(i=0;i<3;i++)
for(j=0;j<4;j++)
for(k=0;k<5;k++)
threed[i][j][k]= i * j *k;
for(i=0;i<3;i++) {
for(j=0;j<4;j++) {
for(k=0;k<5;k++)
System.out.print(threeD[i][j][k] +” “);
System.out.println();
}
System.out.println();
}
}
}
{
public static void main(String [] arg)
{
outer: for(int i=0;i<10;i++){
for(int j=0;j<10;j++){
if(j>i){
System.out.println();
Continue outer;
}
System.out.println(“ “+( i * j));
}
}
System.out.println();
}
}
OBJECT AND CLASSES
class emp
{
String job;
Scanner sc;
public void inp()
{
sc=new Scanner(System.in);
System. out.println(“enter post”);
job=sc.next();
}
public void put()
{
System.out.println(“u r working as “+job);
}
}
class stu
{
String name;
int age;
Scanner sc;
name=sc.next();
age=sc.nextInt();
}
public void put()
{
System.out.println(“hello “+name);
{
public static void main(String [] ar)
{
stu s=new stu();
s.get();
System.out.println(“Enter employee record”);
e.inp();
System.out.println(“Data Input:”);
s.put();
e.put();
}
}
o = new String(“Hello”);
String t;
t = (String) o;
o1=t;//implicit
}
}
class count_word
{
public static void main(String [] as)
{
String n;
int i,wc=1,cc=0,space=0,j;
char c,c1;
Scanner sc=new Scanner(System.in);
System.out.println(“Enter a string”);
n=sc.nextLine();
for(i=0;i<n.length();i++)
{
c=n.charAt(i);
if(c==’ ‘)
{
space++;
wc++;
}
}
cc=n.length()-space;
System.out.println(“Total characters in name are” + cc + “\n
else
System. out.println(“Not”);
}
}
for(int i=1;i<=n;i++)
{
fact=fact*i;
}
System.out.println(“factorial is “+fact);
}
public static void main(String args[]){
new Factorial().fact(5);//calling method with anonymous
object
}
}
{
int length;
int width;
r1.get(11,5);
r2.get(3,15);
r1.calculateArea();
r2.calculateArea();
}
}
{
int acc_no;
String name;
float amount;
void open_account(int a,String n,float amt)
{
acc_no=a;
name=n;
amount=amt;
}
void deposit(float amt)
{
amount=amount+amt;
System.out.println(amt+” deposited”);
}
void withdraw(float amt)
{
if(amount<amt)
{
System.out.println(“Insufficient Balance”);
}
else{
amount=amount-amt;
System.out.println(amt+” withdrawn”);
}
}
void checkBalance()
{System.out.println(“Balance is: “+amount);}
void display()
{System.out.println(acc_no+” “+name+” “+amount);}
}
class TestAccount{
public static void main(String[] args){
Account a1=new Account();
a1. open_account (212345,”Shweta”,10000);
a1.display();
a1.checkBalance();
a1.deposit(40000);
a1.checkBalance();
a1.withdraw(15000);
a1.checkBalance();
}}
40. Write a program to create set() and get() methods to read/ write
values of student data?
class Student
{
int roll_no;
String course;
void set_roll(int r)
{
Roll_no=r;
}
int get_roll()
{
return (roll_no);
}
void set_course(String c)
{
course=c;
}
int get_course()
{
return(course);
}
public static void main(String [] arg)
{
Student s=new Student();
s.set_roll(101);
s.set_course(“java”);
System.out.println(“Roll no”+s.get_roll()+” doing
“+s.get_course);
}
}
CONSTRUCTOR:
or