Durgasoft Core Java Latest1111
Durgasoft Core Java Latest1111
Durgasoft Core Java Latest1111
Introduction to Software
Software is collections of programs such as C , C++ , Java, SQL and other programs.
Software basically two categories:
Software
System software Application Software
it interacts with hardware components for the purpose of application development
Eg: Eg:
Device drivers and Operating systems C, C++, Java, .Net , ERP package and others
Device Drivers:
Operating System:
Durga Soft
#202,2nd Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
2|Page
Application Software
Front End Software Back End Software
These are to interacts with end users These are used to store the data
Eg: Eg:
Languages, Packages ERPs Databases and files
Languages
Low Level Languages High Level Languages
These are machine ( processor ) understandable These are user understandable languages
languages These are looks likes English language
Eg: Easy to understand.
Machine Language (IGL ) and III GL and IV GL are high level languages
Assembly Language (II GL )
Assembly language in the form of pneumonic
codes
Assembler converts assembly language into
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
3|Page
machine language
Generation of Languages
Procedure and Function, both are set of statements to perform some task,
The difference is that, function returns a value whereas procedure does not return a value.
Compliers and interpreters are used to convert high level languages into low level language
( processor understandable language )
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
4|Page
Introduction to JAVA
Features of Java :
1) It is an independent of platform.
3) It is a scalable language.
Platform:
Any hardware or software environment in which a program runs is known as a platform.
Since Java has its own runtime environment (JRE) and API, it is called platform.
JVM is the responsible to make java application as independent of platform and portable
1) It is an independent of platform
Java application runs any operating system and any Hardware
3) It is a scalable language
Easy to use without disturbing the existing java functionality
What is java ?
Java is compile as well as Interpreter based.
Java compiler coverts source code into byte code file
Java Interpreter converts byte code into binary as per the Operating system and Hardware.
Eg:
Any exe file prepared on windows will not execute on Linux and vice versa
Java byte code files not an exe file.
Java Editions:
4 Java FX:
JavaFX is a Java library used to build Rich Internet Applications ( IoT, Internet of Things )
The applications written using this library can run consistently across multiple platforms. The
applications developed using JavaFX can run on various devices such as Desktop Computers,
Mobile Phones, TVs, Tablets, etc..
JavaFX, Java programmers can now develop GUI applications effectively with rich content.
JSE Features:
4) Collections
7) Networking
8) Multi-threading
10) AWT ( Abstract Windowing Tool Kit ) for GUI Applications --> It was outdated concept.
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
6|Page
JEE Features :-
1) Servlets
2) JSP
9) XML Parser
1) Struts Framework
2) Spring Framework
3) Hibernate Framework.
4) Angular JS
5) Node JS
6) Node 2
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
7|Page
There are mainly 6 types of applications that can be created using java programming:
In this applications, data and application both resides in same memory space.
Eg:
java program processing a file data.
C- program processing a file data.
Any Application processing files data.
An application that runs on the server side and creates dynamic page, is called web
application. Currently, servlet, jsp, struts, jsf etc. technologies are used for creating web applications
in java.
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
8|Page
An application that is distributed in nature, such as banking applications etc. It has the
advantage of high level security, load balancing and clustering. In java, EJB is used for creating
enterprise applications.
Durga Soft
#202, 2ndFloor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
9|Page
5) Mobile Application
An application that is created for mobile devices. Currently Android and Java ME are used
for creating mobile applications.
6) IOT Applications:
IoT (Internet of Things) is an advanced automation and analytics system which exploits networking,
sensing, big data, and artificial intelligence technology to deliver complete systems for a product or
service. These systems allow greater transparency, control, and performance when applied to any
industry or system.
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
10 | P a g e
6) Java is an Object Oriented language whereas C++ is a functional oriented as well as Object
oriented language and C – Language is a functional oriented language.
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
11 | P a g e
/*
Developed On :
Developed By :
Modified On :
Modified By :
Reason to Modify :
Description :
import java.lang.String ;
import java.lang.System ;
Name of program file should be same as the class name in which main method is defined.
/* multiple lines
commenting
in java */
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
12 | P a g e
Import java.lang.* ,
import java.lang.String ;
import java.lang.System ;
Eg :
MyFirstExample
WordCountExample ( camel case )
ActionEvent, ActionListener
Java follows camel case syntax for naming the class, interface, method and variable.
public keyword is an access specifier which represents visibility, it means it is visible to all.
No two classes are public in the same program file.
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
13 | P a g e
static is a keyword, if we declare any method as static, it is known as static method. The core
advantage of static method is that there is no need to create object to invoke the static method.
main method is executed by the JVM, so it doesn't require to create object to invoke the main
method. So it saves memory.
main represents start up of the program.
To compile java program main() is not compulsory but to execute main() should presented.
e.g.
getData(), setData(), getEmpInformation()
actionPerformed(), firstName(), etc.
void is the return type of the method, it means it doesn't return any value.
String[] args is used for command line argument. We will learn it later.
println () inserts a new line char at the end of the data, where print() does not.
A blank .java program file can be comiled but not generates .class file
A program file can have multiple classes but not two classes are public
A class must be public, which name is mapped to file name.
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
14 | P a g e
class Sample
{
public static void main(String [] args )
{
System.out.println("Hello NRIT");
}
}
JVM looks for the main(), in a class which is mapped to the file name.
Name Convention
should start with uppercase letter and be a noun e.g. String, Color, Button,
class name
System, Thread etc.
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
15 | P a g e
Overview of JVM
InternalArchitecture, covered at the end of this book.
When a class loader presents the byte codes of a newly loaded Java platform class to the virtual
machine, these byte codes are first inspected by a verifier. The verifier checks that the instructions
cannot perform actions that are obviously damaging. All classes except for system classes are
verified.
Here are some of the checks that the verifier carries out:
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
16 | P a g e
Rules for accessing private data and methods are not violated.
Interpreter :
It coverts java byte code to binary code and prepares as per the current platform (Hardware ) runtime
environment.
JIT :
Just-In-Time (JIT) compiler is a component of the Java Runtime Environment that improves the
performance of Java applications at run time
The JIT compiler helps improve the performance of Java programs by converting byte code into
native machine code at run time.
Garbage Collector :
Garbage collector is a daemon thread. CPU is responsible to call Garbage collector. If there are no
threads running in the system, then CPU makes a call to Garbage collector.
Java provides facitlity to Java developer for invoking Grabage collector through Runtime.gc() /
System.gc()
Thread Schedular:
Security Managar:
Security Managar is to provide the security for local system resources from Java Application.
Interview Questions:
Ans:
Durga Soft
#202, 2ndFloor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
17 | P a g e
Ans:
exe file is a prepared file for specific OS. It contains binary code.
exe file contains, program code, application software libraries, OS libraries and hardware
exe file is a OS dependent.
Ans :
No we can't create exe file. In java every thing is .class file, it is not an exe file
Ans;
.class file is byte code file, which contains only java program code and Java libraries.
Ans;
it is independent of Platform since it does not contain any OS libraries and Hardware
information.
Ans:
exe file contains binary code and .class file contains byte code
exe file is prepared file for specific OS and .class is not prepared file.
After moving .class file to OS, then preparation starts as per current OS.
Ans:
JVM, JRE and JDK are platform dependent because configuration of each OS differs.
But, Java is platform independent.
It contains JRE + Development Tools ( javac, java, javap, javadoc, jar, appletviewer, rmic, jps and
etc )
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
18 | P a g e
Loads code
Verifies code
Executes code
Provides runtime environment
Ans:
Just-In-Time (JIT) compiler is a feature of the run-time interpreter.
It prepares the binary code ( generated by Interpreter ) as per the current OS Specifications.
Ans: yes.
Ans: No
Ans:
java application build can be moved from one OS to another OS with out any changes in the
application build .
Ans : Yes
Ans:
No
A class must be public which name is same as File name.
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
19 | P a g e
Ans: C
A Java-source file with zero class-declarations will not result in any .class files
Place the JDK into C-Drive and run as admin next Accept agreement next …… finish.
System Variable,
Edit PATH
Eg:
C:\ProgramData\Oracle\Java\javapath;%PATH%;C:\app\nagaswarao\product\11.2.0\dbhome_1\bin;
%SystemRoot%\system32;%SystemRoot%;%SystemRoot%\System32\Wbem;%SYSTEMROOT%\
System32\WindowsPowerShell\v1.0\; %JAVA_HOME%\bin;
$gedit ~/.bashc
export JAVA_HOME=/usr/lib/jvm/java-8-openjdk-i386
Durga Soft
#202, 2ndFloor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
20 | P a g e
Eclipse setup:
Take the eclipse zip ( archive ) and place into C-dirve rt.click extract here created short cut on
desk for eclipse.
On launching eclipse, it check for the JAVA_HOME, then integrates jdk with eclise.
Eclipse is an IDE
Java Compiler, JRE, JVM are integrated to eclipse automatically, when PATH variable is defined in
the OS.
1) Workspace
2) Project
3) Package
4) Classes
5) Methods
Step1:
Create Workspace
Launch eclipse Select Work Space location ( browse ) and provide the name , d:\test\SampleWS
Step2:
Create Project
Finish
Step3:
Create package
Durga Soft
#202, 2ndFloor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
21 | P a g e
org Organization
Eg:
com.nrit.tarck.admin
Step4:
Create a class
package com.nrit.mnrao.test;
System.out.println("Hello World");
At Console O/p:
Hello World
Durga Soft
#202, 2ndFloor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
22 | P a g e
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
23 | P a g e
Java char is a unicode character. It is because java uses Unicode system than ASCII code system.
ASCII code system accepts only ASCII chars key board set( 0 to 255 ) .
Java is a net based product, to accept all keyboard sets across the universe it is designed with 2 bytes.
Char with 2 bytes can accept the value ranging from 0 to 65535 ( many keyboard sets )
Durga Soft
#202,2nd Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
24 | P a g e
}
}
Variable :
Variable is a name of memory location.
Declaration of a variable.
data_type variable_name;
eg :
int eno;
double salary;
char gender;
Initialization of a variable:
int eno=1001;
double salary=5000.00;
char gender='M';
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
25 | P a g e
eno=1001;
salary=5000.00;
gender='M';
eg1:
public class Test
{
public static void main(String[] args)
{
int eno = 1001;
double salary = 5000.00;
char gender = 'M';
eno = 1002;
salary = 6000.00;
gender = 'F';
O/p:
Initial Details are :
Emp Number=1001 Salary=5000.0 Gender:M
eg2:
public class Test
{
public static void main(String[] args)
{
int eno=1001;
double salary=5000.50;
int age=30;
char gender='M';
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
26 | P a g e
eno=1002;
salary=6000.50;
age=20;
gender='F';
System.out.println (eno+"\t"+salary+"\t"+age+"\t"+gender);
}
}
int a =10;
int b =20;
int a = 10;
int b = 20;
int temp;
temp = a;
a = b;
b = temp;
System.out.println ("After swapping");
Before swapping
a=10 b=20
After swapping
a=20 b=10
Durga Soft
#202, 2ndFloor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
27 | P a g e
==============
Reading data from keyboard
There are many ways to read data from the keyboard. For example:
InputStreamReader
Console
Scanner
DataInputStream etc.
At this stage, we can focus only on Scanner and others will be discussed in I/O streams.
The Java Scanner class breaks the input into tokens using a delimiter that is whitespace by default.
It provides many methods to read and parse various primitive values.
All methods will read data upto next token ( space or tab or \n, which is coming fisrt), except ,
nextLine()
nextLine() : it will read input data upto eneter key including space and tab. It will read any type of
data.
next() : It will read input data up to space or tab or new line char, which is coming first. It will read
any type of data.
All methods, except nextLine() and next(), can read only numeric data.
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
28 | P a g e
Eg:
package com.nrit.mnrao.test;
import java.util.Scanner;
public class Test {
Type Casting:
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
29 | P a g e
1) implicit casting:
it is a conversion of data from small type to big type. It is an implicit process
( automatically/internally )
Eg:
byte b=10;
short s=b;
eg1:
byte b=10;
short s = b ; --> valid
eg2:
int a=10;
long b=a; --> valid
eg3:
float a=10.5f;
double b=a; --> valid
2) Explicit casting:
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
30 | P a g e
Short a=10;
byte b = (byte ) a ; --> it is valid
short a=130;
byte b = (byte ) a ; --> it compiles but at run time loss of data. It results in unexpected data
( i.e leads to bugs )
float a= 10.5 ; --> invalid, since in java real numbers by default treats as double.
float a= 10.5f; --> valid
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
31 | P a g e
Java Operators
1) Unary Operators
2) Binary Operators
3) Ternary Operators
Binary Operators:
2) Relational Operators
3) Logical Operators
4) Assignment Operator
6) bitwise operators
Operator Task
+ Addition
- Subtraction
* Multiplication
/ Division
% Modula’s ( remainder )
Eg:
10 % 3 =1
3%10 = 3
9%10 = 9
50%51=50
Relational Operators:
Operator Task
> Greater than
>= Greater than or equal to
< Less than
<= Less than or equals to
== Is equal to
!= Not equal to
== --> comparison
= --> assignment.
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
32 | P a g e
Logical Operators:
Operator Task
&& And
|| Or
! Not
Using ( | | ) operator:
Using not ( ! ):
int c=a+b;
System.out.println ("Addition : "+c);
c=a-b;
System.out.println ("Subtraction : "+c);
c=a*b;
System.out.println ("Multiplication : "+c);
}
}
o/p
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
33 | P a g e
Addition : 30
Subtraction : -10
Multiplication : 200
Control Statements
1) if statement.
3) loops
if – statement:
1) simple-if
2) if-else
3) Nested – if
4) ladder -if
Durga Soft
#202,2nd Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
34 | P a g e
Durga Soft
#202,2nd Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
35 | P a g e
int a = 30;
int b = 20;
if (a > b)
{
System.out.println (" a is greater");
}
else
{
System.out.println (" b is greater");
}
}
}
Durga Soft
#202, 2ndFloor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
36 | P a g e
if(a==b)
{
System.out.println ("both are equal");
}
else if(a>b)
{
System.out.println (" a is greater");
}
else
{
System.out.println ("b is greater");
}
}
}
int a = 30;
int b = 50;
int c = 75;
if (a > b)
{
if(a>c)
{
System.out.println (" a is greater");
}
else
{
System.out.println (" c is greater");
}
}
else if (b>c)
{
System.out.println (" b is greater");
}
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
37 | P a g e
else
{
System.out.println (" c is greater");
}
}
}
if all subject are greater than or equal to 40 then pass otherwise fail.
if(sub1>=40)
{
if(sub2>=40)
{
if(sub3>=40)
{
System.out.println ("Pass");
}
else
{
System.out.println ("FAIL");
}
}
else
{
System.out.println ("FAIL");
}
}
else
{
System.out.println ("FAIL");
}
}
}
Durga Soft
#202,2nd Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
38 | P a g e
Another way:
Another way:
if (sub1 < 40 )
{
System.out.println ("FAIL");
}
else if(sub2<40)
{
System.out.println ("FAIL");
}
else if(sub3<40)
{
System.out.println ("FAIL");
}
else
{
System.out.println ("Pass");
}
}
}
Durga Soft
#202,2nd Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
39 | P a g e
Another way:
}
}
}
int sub1=60;
int sub2=80;
int sub3=85;
if(avg >=70)
{
System.out.println ("Grade A with Distinction");
}
else if(avg>=60 )
{
System.out.println ("Grade A ");
}
else if(avg>=50 )
{
System.out.println ("Grade B ");
}
Durga Soft
#202,2nd Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
40 | P a g e
else
{
System.out.println ("Grade c ");
}
}
else
{
System.out.println ("FAIL ");
}
}
if(true)
{
System.out.println ("true part");
}
else
{
System.out.println ("false part");
}
c=a>b;
if(c)
{
System.out.println ("true part");
}
else
{
System.out.println ("else part");
}
c=a<b;
if(c)
{
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
41 | P a g e
c=(a<=b);
if(c)
{
System.out.println ("true part");
}
else
{
System.out.println ("else part");
}
}
}
o/p:
else part
true part
true part
import java.util.Scanner;
public class Test {
if(score<0)
{
System.out.println("Invalid Input");
}
else if(score==0)
{
System.out.println("Duck out");
}
else if(score<50)
{
System.out.println("Normal score");
}
else if(score<100)
{
System.out.println("Half Century");
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
42 | P a g e
}
else if(score<200)
{
System.out.println("Century");
}
else
{
System.out.println("Double Century");
}
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
43 | P a g e
If value is not matching with any of the constants, then default case executes.
break statement will take the control out of the switch case.
If break is not presented in any of the case block then next case block also executes till next break.
Durga Soft
#202, 2ndFloor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
44 | P a g e
int a=10;
switch (a)
{
case 10:
System.out.println ("TEN");
break;
case 20:
System.out.println ("Twenty");
break;
case 30:
System.out.println ("Thirty");
break;
case 40:
System.out.println ("Fourty");
break;
default:
System.out.println ("DEFAULT");
break;
}
System.out.println ("after switch case");
}
}
import java.util.Scanner;
int a=sc.nextInt();
int b=sc.nextInt();
System.out.println("Menu");
System.out.println("1.Addition ");
System.out.println("2.Subtraction ");
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
45 | P a g e
System.out.println("3.Multiplication ");
System.out.println("Enter your choice 1/2/3 : ");
switch( choice )
{
case 1:
System.out.println("Addition = "+(a+b));
break;
case 2:
System.out.println("Subtraction = "+(a-b));
break;
case 3:
System.out.println("Multilication = "+(a*b));
break;
default:
System.out.println("Wrong choice");
break;
}
Unary Operator:
It works with only one operand.
Eg:
int a=10;
Increment Operator ( ++ ) :
Durga Soft
#202,2nd Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
46 | P a g e
Decrement operator ( - - ):
Increment Operator ( ++ ) :
2)It increase value of it's Operand by 1 before 2)It increase value of it's Operand by 1 after
executing statement executing statement
3) eg : 3) eg :
int a=10; int a=10;
int b = ++a: --> a=11, b=11 int b = a++: -->b=10, a=11
int b;
int c;
int d;
b=++a;
c=b++;
d=++c;
System.out.println (a+"\t"+b+"\t"+c+"\t"+d);
}
}
O/p : 11 12 12 12
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
47 | P a g e
b=a++;
c=++b;
d=c++;
b=d++;
a=++c;
System.out.println (a+"\t"+b+"\t"+c+"\t"+d);
}
}
O/P : 13 11 13 12
d=++a;
b=d++;
a=++b;
c=d++;
d=++c;
System.out.println (a+"\t"+b+"\t"+c+"\t"+d);
}
}
O/P :
12 12 13 13
Decrement Operator ( - - ) :
2)It decreases value of it's Operand by 1 before 2)It decreases value of it's Operand by 1 after
executing statement executing statement
3) eg : 3) eg :
int a=10; int a=10;
int b = --a: --> a=9, b=9 int b = a--: -->b=10, a=9
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
48 | P a g e
int c;
int d;
b=--a;
c=b++;
d=--c;
a=++b;
d=a--;
System.out.println (a+"\t"+b+"\t"+c+"\t"+d);
}
}
O/P :
10 11 8 11
d = a--;
b = ++d;
c = a++;
a = --b;
d = c++;
10 10 10 9
Eg1:
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
49 | P a g e
int a=10;
int b=15;
value of c is 25
Eg2:
int a=20;
int b=15;
value of c is 5
Loops:
1) while loop
2) do – while loop
3) for – loop
loops are used to execute same statements again and again ( iterative statements )
while loop:
Syntax:
while( Cond )
{
=========;
========;
========;
========;
}
To display 1 to 10
Durga Soft
#202, 2ndFloor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
50 | P a g e
int i=1;
while(i<=10)
{
System.out.println (i);
i++;
}
}
}
To display 10 to 1
while(i>=1)
{
System.out.println (i);
i--;
}
}
To display 1 to n
while(i<=n)
{
System.out.println (i);
i++;
}
}
}
do-while:
syntax:
do
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
51 | P a g e
{
=======;
=======;
======;
======;
}
while(cond) ; --> here semicolon required.
do
{
System.out.println (i);
i++;
}
while(i<=10);
}
}
Even Numbers:
int i=1;
while(i<=20)
{
if(i%2==0)
{
System.out.println (i);
}
i++;
}
}
}
Odd Numbers :
Durga Soft
#202, 2ndFloor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
52 | P a g e
while(i<=20)
{
if(i%2!=0)
{
System.out.println (i);
}
i++;
}
}
}
for – loop:
syntax:
Durga Soft
#202,2nd Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
53 | P a g e
{
for( int i=1; i<=20; i++)
{
if(i%2==0)
{
System.out.println (i);
}
}
}
}
while(i<=10)
{
sum=sum+i;
i++;
}
System.out.println (sum);
}
}
Durga Soft
#202,2nd Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
54 | P a g e
{
int i=1;
int esum=0;
int osum=0;
while( i <=10)
{
if(i%2==0)
{
esum=esum+i;
}
else
{
osum=osum+i;
}
i++;
}
System.out.println ("Even sum = "+esum);
System.out.println ("Odd sum = "+osum);
}
}
using for loop:
1 2 3 5 5 8 7 11 9 14 11 17 13 20
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
55 | P a g e
Durga Soft
#202, 2ndFloor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
56 | P a g e
{
int n=11;
boolean flag = true;
int i=2;
while(i<=n/2)
{
if(n%i==0)
{
flag=false;
break;
}
i++;
}
if(flag==true)
{
System.out.println ("prime number");
}
else
{
System.out.println ("not a prime number");
}
}
}
it takes the control to beginning of the loop ( condition ) and skips the rest of the loop
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
57 | P a g e
while(i<=n)
{
if(i%2!=0)
{
i++;
continue;
}
System.out.println (i);
i++;
}
}
}
1*1=1
1*2=2
1*3=3
1*4=4
1*5=5
1*6=6
1*7=7
1*8=8
1*9=9
1 * 10 = 10
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
58 | P a g e
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4 5
1 2 3 4
1 2 3
1 2
1
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
59 | P a g e
}
}
}
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
16 17 18 19 20 21
System.out.println ();
n++;
}
}
}
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
60 | P a g e
Palindrome number
Durga Soft
#202,2nd Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
61 | P a g e
Input: 12321
Input: 329
Input: 5
Output: 120
Input: 6
Output: 720
1 1
1 2 2 1
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
62 | P a g e
1 2 3 3 2 1
1 2 3 4 4 3 2 1
1 2 3 4 5 4 3 2 1
1 2 3 4 4 3 2 1
1 2 3 3 2 1
1 2 2 1
1 1
Below Triangle
1 1 1 1 1 1 1 1 1
2 2 2 2 2 2 2
3 3 3 3 3
4 4 4
4 4 4
3 3 3 3 3
2 2 2 2 2 2 2
1 1 1 1 1 1 1 1 1
1 2 3 4 5 4 3 2 1
1 2 3 4 4 3 2 1
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
63 | P a g e
1 2 3 3 2 1
1 2 2 1
1 1
1 2 2 1
1 2 3 3 2 1
1 2 3 4 4 3 2 1
1 2 3 4 5 4 3 2 1
Arrays
Array is a collections of similar type of elements
Arrays are objects in java.
declaration :
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
64 | P a g e
initializing an array :
length :
it is a variable provided by JVM . it is not from any pre-package ( such as java.lang)
a=new int[6];
b=new int[9];
c=new int[8];
Durga Soft
#202,2nd Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
65 | P a g e
}
}
}
}
1) int a[];
a=new int[5];
a[0]=10;
a[1]=15;
a[2]=21;
a[3]=25;
a[4]=30;
3) int a[]={1,2,3,4,5};
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
66 | P a g e
int max=a[0];
int min=a[0];
for(int i=1;i<a.length;i++)
{
if(a[i]>max)
{
max=a[i];
}
if(a[i]<min)
{
min=a[i];
}
}
System.out.println ("max ="+max);
System.out.println ("min ="+min);
}
}
for (int i : a)
{
System.out.println (i);
}
}
}
Array of Strings:
It is a collection of strings.
String is a class from java.lang package to handle the strings.
Durga Soft
#202, 2ndFloor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
67 | P a g e
{
String [] names={"hadoop","java","html","oracle","hive","sqoop","pig"};
}
}
Searching Techniques:
1) Linear search
2) Binary search
Linear search:
It is a searching for the element from the beginning to end .
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
68 | P a g e
int num=55;
boolean flag=false;
for(int i=0;i<a.length;i++)
{
if(num==a[i])
{
flag=true;
System.out.println ("your num found at a["+i+"]");
break;
}
}
if(flag==false)
{
System.out.println ("your number not found");
}
}
}
Binary Search:
It is a searching for the elements in half of the actual number of elements each iteration.
int num=86;
boolean flag=false;
while(l<=h)
{
int m=(l+h)/2;
if(num==a[m])
{
flag=true;
System.out.println ("your number found at a["+m+"]");
break;
}
else if(num>a[m])
{
l=m+1;
}
else
Durga Soft
#202, 2ndFloor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
69 | P a g e
{
h=m-1;
}
if(flag==false)
{
System.out.println ("Your number not found");
}
}
}
Note:
1) In linear search numbers can be random order.
2) In Binary search numbers must be in ascending / descending order.
Bubble Sorting:
for(int i=0;i<a.length;i++)
{
System.out.print(a[i]+"\t");
}
//bubble sorting
for(int i=0;i<a.length-1;i++)
{
for(int j=0;j<a.length-1-i;j++)
{
if(a[j]>a[j+1])
{
int temp = a[j];
a[j] = a[j+1];
a[j+1]=temp;
}
}
for(int i=0;i<a.length;i++)
{
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
70 | P a g e
System.out.print(a[i]+"\t");
}
}
}
ArraySort.java
package com.nrit.mnrao.test;
import java.util.Arrays;
Arrays.sort(strArr);
System.out.println(Arrays.toString(intArr));
System.out.println(Arrays.toString(strArr));
}
$gedit Test.java
Durga Soft
#202,2nd Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
71 | P a g e
{
public static void main( String [] args)
{
int n = args.length;
execution:
$java Test hello java world
o/p:
No.of elements=3
$gedit Test.java
}//main closing
}//class closing
compilation:
$javac Test.java
execution:
$java Test hello java world
hello
java
world
Displaying command line parameters using for-each loop:
Durga Soft
#202,2nd Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
72 | P a g e
}
}
}
2-Dimensional Array
If you know how to create one dimensional array and fact that multi-dimensional arrays are just array
of array in Java, then creating a 2 dimensional array is very easy. Instead of one bracket, you will use
two
int [][] matrix = new int[4][2]; // 2D integer array with 4 rows and 2 columns
String [][] cities = new String[3][3]; // OK , 2D String array with 3 rows and 3 columns
String [][] yourArray = new String[5][4]; // OK
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
73 | P a g e
int [][] wrong = new int[][]; // Invalid, you must specify 1st dimension
Eg:
a.length no of rows
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
74 | P a g e
1 2 3
4 5 6
7 8 9
for(int j=0;j<a[i].length;j++)
{
System.out.print(a[i][j]+"\t");
}
}
}
}
for(int j=0;j<a[i].length;j++)
{
System.out.print(a[i][j]+"\t");
}
}
}
}
1
1 2
1 2 3
1 2 3 4
1st step:
2nd step:
assigning values:
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
76 | P a g e
for(int i=0;i<a.length;i++)
{
for(int j=0;j<a[i].length;j++)
{
a[i][j]=j+1;
}
}
Display:
for (int i = 0; i < a.length; i++)
{
System.out.println ();
for (int j = 0; j < a[i].length; j++)
{
System.out.print(a[i][j] + "\t");
}
}
a= new int[4][];
for(int i=0;i<a.length;i++)
{
a[i] = new int[i+1];
}
for(int i=0;i<a.length;i++)
{
for(int j=0;j<a[i].length;j++)
{
a[i][j]=j+1;
}
}
System.out.println ("elements");
for(int i=0;i<a.length;i++)
{
System.out.println ();
for(int j=0;j<a[i].length;j++)
{
System.out.print(a[i][j]+"\t");
}
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
77 | P a g e
}
}
Durga Soft
#202,2nd Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
78 | P a g e
syntax:
Access_specifier Return_type method_name ( type arg1, type arg2, type arg3, ......)
{
============;
============;
============;
============;
============;
return value;
}
Access_specifier :
1) public
2) protected
3) private.
4) nothing ( default )
Return_type:
Eg:
return 10; --> return type is int.
eg:
Method with no args and no return value
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
79 | P a g e
Calling a method:
eg:
public class Test
{
public static void main(String[] args)
{
System.out.println ("main start");
display();
O/p:
main start
I am in display
main end
Durga Soft
#202,2nd Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
80 | P a g e
display();
show();
Main start
Before display
I am in display
After display
Before show
I am in show
after show
Main End
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
81 | P a g e
display();
show();
show();
O/P:
main start
before display
display start
I am in show
display end
after display
before show
I am in show
after show
main end
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
82 | P a g e
Recursive method:
eg:
public void display()
{
System.out.println ("I am in display");
display();
Recursive methods are not recommended. There is a chance of raising stack over flow error.
display(a,b);
show(50,60);
}//main close
}//display close
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
83 | P a g e
Main start
I am in display
args are 10 20
After display
Before show
I am in show
args are 50 60
after show
Main End
c = subNum(a, b);
c = mulNum(a,b);
}//main close
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
84 | P a g e
addition 30
substraction -10
multiplication 200
Eg:
public void display(int x, int y)
{
================
================
if(cond)
{
return ;
}
================
================
}
Sample program.
greater(a,b);
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
85 | P a g e
a=20;
b=30;
greater (a,b);
if(x>y)
{
return ;
}
O/P;
Main start
greater start
after greater one
greater start
greater end // only one time as condition is true for the first time.
after greater two
Main end
Interview Questions
Durga Soft
#202, 2ndFloor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
86 | P a g e
Ans: break and continue are two important keywords used in Loops. When a break keyword is used
in a loop, loop is broken instantly while when continue keyword is used, current iteration is broken
and loop continues with next iteration.
Ans: In Java, package is a collection of classes and interfaces which are bundled together as they are
related to each other. Use of packages helps developers to modularize the code and group the code
for proper re-use. Once code has been packaged in Packages, it can be imported in other classes and
used.
Ans:
java.lang package is a default available package in the java applications, hence import not required.
One of the Java 7 feature was improvement of switch case of allow Strings. So if you are using Java
7 or higher version, you can use String in switch-case statements.
Heap memory is used by all the parts of the application whereas stack memory is used only by one
thread of execution.
Whenever an object is created, it’s always stored in the Heap space and stack memory contains the
reference to it. Stack memory only contains local primitive variables and reference variables to
objects in heap space.
Memory management in stack is done in LIFO manner whereas it’s more complex in Heap
memory because it’s used globally.
The task of java compiler is to convert java program into bytecode, we have javac executable for
that. So it must be stored in JDK, we don’t need it in JRE and JVM is just the specs.
Durga Soft
#202, 2ndFloor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
87 | P a g e
Platform independence means that you can run the same Java Program in any Operating System. For
example, you can write java program in Windows and run it in Mac OS.
Java Virtual Machine (JVM) is the heart of java programming language. JVM is responsible for
converting byte code into machine readable code. JVM is not platform independent, thats why you
have different JVM for different operating systems. We can customize JVM with Java Options, such
as allocating minimum and maximum memory to JVM. It’s called virtual because it provides an
interface that doesn’t depend on the underlying OS.
Java Development Kit (JDK) is for development purpose and JVM is a part of it to execute the java
programs.
JDK provides all the tools, executables and binaries required to compile, debug and execute a Java
Program. The execution part is handled by JVM to provide machine independence.
Java Runtime Environment (JRE) is the implementation of JVM. JRE consists of JVM and java
binaries and other classes to execute any program successfully. JRE doesn’t contain any development
tools like java compiler, debugger etc. If you want to execute any java program, you should have
JRE installed.
PATH is an environment variable used by operating system to locate the executables. That’s why
when we install Java or want any executable to be found by OS, we need to add the directory
location in the PATH variable.
Classpath is specific to java and used by java executables to locate class files. We can provide the
classpath location while running java application and it can be a directory, ZIP files, JAR files etc.
Java ternary operator is the only conditional operator that takes three operands. It’s a one liner
replacement for if-then-else statement and used a lot in java programming. We can use ternary
operator if-else conditions or even switch conditions using nested ternary operators.
that have similar functionality at the same time, and hence reduces the amount of time needed for
compilation.Here the term “compiler” refers to a translator from the instruction set of a Java virtual
machine (JVM) to the instruction set of a specific CPU.
Yes, save your java file by .java only, compile it by javac .java and run by java yourclassname
Let's take a simple example:
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
88 | P a g e
Just-In-Time(JIT) compiler:It is used to improve the performance. JIT compiles parts of the byte
code
23) If I don't provide any arguments on the command line, then the String array of Main
method will be empty or null?
24) What if I write static public void instead of public static void?
Program compiles and runs properly.
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
89 | P a g e
OOP's Concept
Object Oriented Programming was introduced to overcome the dis advantages of C-Language.
C-Language dis-advantages:
Since everything is global, there is no security for data. Chance of corrupting data in C-Language.
1) Encapsulation
2) Data abstraction
3) Method overloading
4) Constructors
5) Inheritance
6) polymorphism
Any language which supports all the above features, that language is called as Object Oriented
Programming Language.
Encapsulation :
Data abstraction :
It is a hiding data from the outside environment; it can be achieved through the encapsulation.
Purpose of data abstraction is for data security.
Method Overloading :
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
90 | P a g e
Constructors:
Inheritance:
Polymorphism:
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
91 | P a g e
Defining a class :
class members does not acquire memory with out creating an object.
Object :- It is an instance of the class. When object is created all the members of the class acquires
memory. It is collection of data members and methods to manipulate or update the data.
Creating an object :
Durga Soft
#202, 2ndFloor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
92 | P a g e
Invoking methods :
s1.setData();
s2.setData();
--------------
s1.display();
s2.display();
if any method is invoking through object, then it must be a member of that class.
eg:
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
93 | P a g e
{
public static void main(String[] args)
{
Sample s1 = new Sample();
Sample s2 = new Sample();
Sample s3 = new Sample();
s1.setData();
s2.setData();
s3.setData();
s1.display();
s2.display();
s3.display();
}
}
O/p:
a=10 b=30.5
a=10 b=30.5
a=10 b=30.5
By new keyword
By newInstance() method
By clone() method
By deserialization
By factory method etc.
Anonymous object
Anonymous simply means nameless. An object which has no reference is known as anonymous
object. It can be used at the time of object creation only.
Eg:
new Sample().setData();
new Sample().display();
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
94 | P a g e
s1.setData(10,20);
s2.setData(30,40);
s3.setData(25,35);
s1.display();
s2.display();
s3.display();
}
}
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
95 | P a g e
Students information:
public void setData(int id, String name, int age, double fee)
{
studentId = id;
studentName = name;
studentAge = age;
studentFee = fee;
}
public void display()
{
System.out.println ("STUDENT DETAILS ARE");
System.out.println ("ID="+studentId);
System.out.println ("NAME="+studentName);
System.out.println ("AGE="+studentAge);
System.out.println ("FEE="+studentFee);
}
}
public class Test
{
public static void main(String[] args)
{
Student st1 = new Student();
st1.setData(1001,"xyz",23,1500);
st2.setData(1002,"abc",24,2000);
st3.setData(1003, "ijk",25,2500);
st1.display();
st2.display();
st3.display();
}
Durga Soft
#202, 2ndFloor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
96 | P a g e
Emplyee information:
public void setData(int eno, String name, double salary, String dept)
{
empNumber = eno;
empName = name;
empSalary = salary;
empDept = dept;
}
e1.setData(1001,"nrit1",5000,"dev");
Durga Soft
#202, 2ndFloor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
97 | P a g e
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
98 | P a g e
employee.setEmpNum(1001);
employee.setEmpName("NRIT1");
employee.setEmpSalary(5000);
employee.setEmpDept("dev");
employee.display();
employee.setEmpName("NRIT2");
employee.setEmpDept("Admin");
employee.display();
employee.setEmpSalary(7000);
employee.display();
}
}
Method Overloading
Method overloading takes place between the same method with different signature
Method signature defines, name of the method, no.of args, type of args and return type of the
method.
Eg:
Overloading based of no.of arguments :
s1.display();
s1.display(10);
s1.display(20, 30);
Durga Soft
#202, 2ndFloor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
100 | P a g e
c = 0;
}
public void setData(int x, int y, int z) {
a = x;
b = y;
c = z;
}
public void display() {
System.out.println ("a="+a+"\tb="+b+"\tc="+c);
}
}
s1.setData();
s2.setData(15);
s3.setData(10,20);
s4.setData(15,25,30);
Durga Soft
#202, 2ndFloor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
101 | P a g e
}
public class Test
{
public static void main(String[] args)
{
int i=10;
float f=30.5f;
char c='a';
s1.setData();
s1.display();
s1.setData(i,f);
s1.display();
s1.setData(i,c);
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
102 | P a g e
s1.display();
}
}
Note :
Method Overloading never check for return type.
any data can be passed to any type of argument, if size of data is less than the size of argument.
char, byte, short and int can be passed to int type of argument.
Ans: Encapsulation is a concept in Object Oriented Programming for combining properties and
methods in a single unit.
Encapsulation helps programmers to follow a modular approach for software development as each
object has its own set of methods and variables and serves its functions independent of other objects.
Encapsulation also serves data hiding purpose.
Java static
Static is an access modifier in java
The static keyword in java is used for memory management mainly. We can apply java static
keyword with variables, methods, blocks and nested class. The static keyword belongs to the class
than instance of the class.
If you declare any data member as static, it is known static data member.
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
103 | P a g e
The static variable can be used to refer the common property of all objects (that is not unique for
each object) e.g. company name of employees, college name of students etc.
The static variable gets memory only once in class area at the time of class loading.
All static members of the class acquire memory without creating an object. These are not part of
object.
For static data members only one copy will be created and that can be shared by all objects of the
class.
It is a sharable memory.
Eg:
class Test {
int a, b ;
static int n :
}
there are three objects created for the above class, for static data member 'n' only one copy is created
but for non static member 'a' and 'b' separate copy is created for ever object ( three copies ).
Durga Soft
#202, 2ndFloor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
104 | P a g e
private int n;
private static int counter;
s1.setData();
s2.setData();
s3.setData();
s1.display();
s2.display();
s3.display();
}
}
O/p:
current Object : 1
Total Objects : 3
current Object : 2
Total Objects : 3
current Object : 3
Total Objects : 3
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
105 | P a g e
s1.setData();
s2.setData();
s3.setData();
s1.display();
s2.display();
s3.display();
}
}
O/P:
Current Object : 1
Total no of Objects : 1
Current Object : 1
Total no of Objects : 1
Current Object : 1
Total no of Objects : 1
All static members of the class acquire memory with reference of class name without creating an
object.
These members can be accessed either through object or by the class name.
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
106 | P a g e
Test.n;
Since static data members acquire memory with reference of the class, these are called as class
variable.
System.out.println (Sample.counter);
Sample.counter=Sample.counter+10;
Sample.counter=Sample.counter+20;
System.out.println (Sample.counter);
O/p: 0 30
Types of variables :
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
107 | P a g e
1) local variables
2) instance variables
3) class variables
eg:
}
}
In real time applications data members are private to achieve data security .
To access these private members, public methods are introduced.
Public methods are acting as interface between private data and outside environment.
Eg:
private int a;
private int b;
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
108 | P a g e
}
}
Static method :
Static methods also like a static data members, it acquires memory without creating an object.
All static members acquires memory by the name of the class without creating an object.
class Test
{
public static void display()
{
=============;
=============;
}
}
static method acquires memory as soon as class gets loaded into the memory (without any class
instance)
Static method can be called by the reference of class name or though the object.
Eg :
calling by the class name --> Test.display();
Durga Soft
#202, 2ndFloor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
109 | P a g e
private int n;
private static int counter;
Sample.showCount();
s1.setData();
s2.setData();
s3.setData();
s1.display();
s2.display();
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
110 | P a g e
s3.display();
Sample.showCount();
}
}
Static method can access only static data members and static methods
Reason:
Static method acquires memory without any object but for non static members object is required.
non static method can access any member ( static or non static members )
private int x;
Durga Soft
#202, 2ndFloor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
111 | P a g e
s1.setData(10);
s1.display();
}
}
O/p: 0
Yes, we can have multiple methods with name “main” in a single class. However if we run the class,
java runtime environment will look for main method with syntax as public static void main(String []
args).
static keyword can be used with class level variables to make it global i.e all the objects will share
the same variable.
static keyword can be used with methods also. A static method can access only static variables of
class and invoke only static methods of the class.
We can’t declare a top-level class as static however an inner class can be declared as static. If inner
class is declared as static, it’s called static nested class.
Static nested class is same as any other top-level class and is nested for only packaging convenience.
Java static block is the group of statements that gets executed when the class is loaded into memory
by Java ClassLoader. It is used to initialize static variables of the class. Mostly it’s used to create
static resources when class is loaded.
main method is public and static so that java can access it without initializing the class. The input
parameter is an array of String through which we can pass runtime arguments to the java program.
Durga Soft
#202, 2ndFloor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
112 | P a g e
import java.lang.Math;
//inside class
double test = Math.PI * 5;
We can do the same thing by importing the static method or variable only and then use it in the class
as if it belongs to it.
Use of static import can cause confusion, so it’s better to avoid it. Overuse of static import can make
your program unreadable and unmaintainable.
8) What is difference between object oriented programming language and object based
programming language?
Object based programming languages follow all the features of OOPs except Inheritance. Examples
of object based programming languages are JavaScript, VBScript etc.
9) What if the static modifier is removed from the signature of the main method?
Program compiles. But at runtime throws an error "NoSuchMethodError".
10) What is difference between static (class) method and instance method?
12. How we can execute any code even before main method?
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
113 | P a g e
Ans: If we want to execute any statements before even creation of objects at load time of class, we
can use a static block of code in the class. Any statements inside this static block of code will get
executed once at the time of loading the class even before creation of objects in the main method.
In java, this is a reference variable ( pointer ) that refers to the current object.
When object is created, for each and every object this pointer generates and stores address of same
object.
Hence this pointer refer to the current object.
2) if class data member name and method argument names are same, to access class data
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
114 | P a g e
3) if class data member name and local variable name is same, to access class data member we
can use this keyword.
4) this keyword can also be used to return the current class instance.
When over object is created for every object reference variable will be created.
Accessing :
this.member;
if class data member name and method argument name are same, to access class data member we can
use this keyword.
eg:
private int x;
Durga Soft
#202, 2ndFloor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
115 | P a g e
s1.setData(10);
s1.display();
}
}
if class data member name and local variable name is same, to access class data member we can use
this keyword.
When object is created, for each and every object this pointer generates and stores the address of
same object.
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
116 | P a g e
Durga Soft
#202, 2ndFloor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
117 | P a g e
employee1.setEmpNum(1001);
employee1.setEmpName("nrit1");
employee1.setEmpSalary(5000);
employee1.setEmpGender('M');
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
118 | P a g e
employee2.setEmpNum(1002);
employee2.setEmpName("nrit2");
employee2.setEmpSalary(6000);
employee2.setEmpGender('F');
Class with setter and getter methods is called POJO class or bean class or model class.
int a;
int b;
public void setData(int x, int y)
{
a=x;
b=y;
}
public void display()
{
System.out.println(a+"\t"+b);
}
s1.setData(10, 20);
Sample s2 = s1;
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
119 | P a g e
s1.display();
s2.display();
O/p: 10 20
10 20
Passing variable to method is a call by value. For variables no call by reference concept in java.
int a=10;
int b=20;
swap(a,b);
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
120 | P a g e
In call by value the changes made on the arguments will not be reflected on the actual variables (
passing variables)
Passng object to method is a call by reference in java. There is no call by value concept for
objects.
updateData(s1);
x.setData(50, 60);
}
}
=============================
Another eg:
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
121 | P a g e
return empNum;
}
employee.setEmpNum(1001);
employee.setEmpName("nrit");
employee.setSalary(5000);
employee.setEmpDept("admin");
System.out.println("data delivering....");
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
122 | P a g e
sendData(employee);
System.out.println("data delivered");
}
Another eg:
public class Test
{
public static void main(String[] args) {
System.out.println("data receiving....");
recvData(employee);
System.out.println("data received");
System.out.println(empNum+"\t"+empName+"\t"+salary+"\t"+empDept);
}
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
123 | P a g e
Another Eg:
System.out.println("data receiving....");
recvData1(employee);
System.out.println("data received");
System.out.println(empNum+"\t"+empName+"\t"+salary+"\t"+empDept);
}
private int a;
private int b;
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
124 | P a g e
}
public void display()
{
System.out.println(a+"\t"+b);
}
s1.setData(10, 20);
Sample s2 = s1.myCopy();
s1.display();
s2.display();
O/p: 10 20
10 20
This keyword (pointer ) should not be used in the static methods, because static method acquires
memory without creating an object but “this” reference will not be created without any object.
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
125 | P a g e
Since static method do not have current object, this key word should not be used with static methods.
Eg:
public class Sample {
private int a;
int a = 50;
System.out.println(this.a);// invalid
}
this keyword provides reference to the current object and it’s mostly used to make sure that object
variables are used, not the local variables having same name.
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
126 | P a g e
Constructors
Constructor is a member of the class, it is like a method, which is invoked automatically when object
is created.
3) Constructor should not have any return type not even void also. Implicitly it returns its own type.
6) constructor should not be static, abstract, final, synchronize, transient, native and volatile
Types of constructors :
public Sample()
{
System.out.println ("Constructor called");
}
}
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
127 | P a g e
Initializing an object :
public Sample()
{
a=10;
b=20.6f;
ch='a';
}
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
128 | P a g e
default constructors are used to initialize all objects with same values.
Method can not be invoked through the null reference. It throws NullPointerException
Eg: min balance in bank account and min age of employment is same for all.
Company name is same for all employes
Another example :
empNum and salary auto initialization.
public Employee()
{
empNum=++counter; // assigning empnum automatically
empSalary=5000;// default salary for any employee.
}
Durga Soft
#202, 2ndFloor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
129 | P a g e
@Override
public String toString() {
return "Employee [empNum=" + empNum + ", empName=" + empName + ",
empSalary=" + empSalary + ", empGender="
+ empGender + "]";
}
}
System.out.println(employee1);
System.out.println(employee2);
System.out.println(employee3);
System.out.println(employee4);
}
}
Eg:
Another example:
public DatabaseServer()
Durga Soft
#202, 2ndFloor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
130 | P a g e
{
dbHost="localhost";
dbName="nrit";
dbUid="scott";
dbPasswd="tiger";
}
Durga Soft
#202, 2ndFloor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
131 | P a g e
db.setDbHost("192.10.20.1");
db.display();
db.setDbUid("java");
db.setDbPasswd("java123");
db.display();
public Sample() {
a = 10;
b = 20;
}
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
132 | P a g e
s1.display();
s2.display();
s3.display();
}
}
class Test {
private int a, b ;
public Test() {
a=0;
b=0;
}
public Test(intx, int y) {
a=x;
b=y;
}
void display() {
System.out.println ( “ a= “ + a + “ b= “ +b);
}
}
public class MultiConstructorTest {
Test t1 = new Test(); // if default constructor is not defined then it is a compilation error.
t1.display();
t2.display();
}
}
if default constructor is not defined, then compiler generates a default constructor for every class.
If class contains at least one user defined constructor, then compiler will not generate default
constructor.
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
133 | P a g e
If class contains constructors then one of the constructors must be a default constructor.
Eg:
private int a;
private int b;
s1.display();
s2.display();
s3.display();
}
}
Constructor overloading :
At compile time compiler first check for the no.of args, if no.of args are matched then checks for the
type args, if type is also matched between constructors then ambiguity between the constructors and
compilation error.
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
134 | P a g e
public Test() {
a=0;
b=0;
c=0;
}
public Test(int x) {
a=x;
b=0;
c=0;
}
public Test(int x, int y) {
a=x;
b=y;
c=0;
}
public Test(int x, int y, int z) {
a=x;
b=y;
c=z;
}
void display() {
System.out.println ( “ a= “ + a + “ b= “ +b+” c= “ +c);
}
}
t1.display();
t2.display();
t3.display();
}
}
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
135 | P a g e
class Test {
private int a;
private float b;
private char ch;
public Test() {
a=0;
b=0.0f;
ch=0;
}
void display() {
int i=10;
float f = 11.5f;
char c1 = 'a';
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
136 | P a g e
t1.display();
t2.display();
t3.display();
}
}
1) Class Level
2) Initialize block
3) Constructor
class Test {
initialize block :
class Test {
{
======;
======;
======;
}
}
public Sample()
{
System.out.println ("constructor");
}
}
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
137 | P a g e
public Sample()
{
System.out.println ("constructor");
}
{
System.out.println ("Initialize block2");
}
{
System.out.println ("Initialize block3");
}
}
}
}
There is no order of writing initialize blocks, it can be written anywhere in the class.
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
138 | P a g e
If class contains multiple initialize blocks then order of execution is top to bottom.
Purpose of Multiple initialize blocks are to segregate constants for easy understanding code ( as per
coding standards )
Segregate grouping.
Static block :
class Test {
static {
========;
========;
}
}
Eg:
class Test {
static
{
System.out.println ( “ Static block “);
}
{
System.out.println ( “ Init block “);
}
public Test() {
System.out.println (“ Constructor “);
}
}
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
139 | P a g e
constructor
Static block is executed only for the first time created object. Because it is common for all the
objects.
A class can have multiple static blocks. The order of execution is from top to bottom.
The purpose of static block is to initialize the static constants.
Purpose multiple static blocks are to segregate mutilple static constants.
public Sample()
{
System.out.println("default constructor");
}
public Sample(int x, int y)
{
this();
System.out.println("two args");
}
public Sample(int x, int y, int z)
{
this(10,20);
System.out.println("three args");
}
}
}
}
O/P:
default constructor
two args
three args
the statement, which makes a call to another constructor must be 1st statement inside the constructor.
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
140 | P a g e
Eg:
public class Sample {
public Sample()
{
System.out.println("default constructor");
}
public Sample(int x, int y)
{
System.out.println("two args");
this();// invalid compile time error.
}
public Sample(int x, int y, int z)
{
System.out.println("three args");
this(10,20);// invalid compile time error.
}
}
public Sample()
{
System.out.println("default constructor");
}
public Sample(int x, int y)
{
System.out.println("two args");
}
public Sample(int x, int y, int z)
{
this(10,20,30); // Recursive caling is not valid for constructors.
System.out.println("three args");
}
}
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
141 | P a g e
Ans: The constructor of a class is invoked every time an object is created with new keyword.
Ans: Yes, a class can have multiple constructors with different parameters. Which constructor gets
used for object creation depends on the arguments passed while creating the objects.
Ans: Even if no explicit constructor is defined in a java class, objects get created successfully as a
default constructor is implicitly used for object creation. This constructor has no parameters.
4. Can we call the constructor of a class more than once for an object?
Ans: Constructor is called automatically when we create an object using new keyword. It’s called
only once for an object at the time of object creation and hence, we can’t invoke the constructor
again for an object after its creation.
Ans: We can define two methods in a class with the same name but with different number/type of
parameters. Which method is to get invoked will depend upon the parameters passed.
Durga Soft
#202, 2ndFloor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
142 | P a g e
Inheritance
It is an acquiring parent properties into child.
Def. : It is a creation of new classes from existing classes. It as an acquiring old class properties into
new class.
Types of inheritance :
1) Single inheritance
3) Hierarchical Inheritance
1) Single inheritance
Syntax :
class Parent {
=============;
=============;
=============;
=============;
=============;
=============;
}
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
143 | P a g e
A class can extend from only single class, since java does not support multiple inheritance
Dis-advantage of multiple inheritance, chance creating duplicate copies at the child class level.
Eg:
public class Sample {
int a;
int b;
}
}
int c;
int d;
t1.setData(10,20,30,40);
t1.display();
}
}
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
144 | P a g e
Eg:
Parent class and child class contains same methods with same signature then method Overriding
takes place.
t1.display();
o/p : Test
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
145 | P a g e
t1.display();
}
}
Super class method can be called from anywhere from the child class Method.
Eg:
public void display()
{
System.out.println ("Test");
super.display();
}
Another example :
Invoking current class methods and parent class methods.
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
146 | P a g e
Eg:
Another example
int a;
int b;
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
147 | P a g e
int c;
int d;
t1.setData(1,2,3,4);
t1.display();
}
}
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
148 | P a g e
class Test {
void display() {
System.out.println ( “ Test display “ );
}
}
super.display();
t1display();
}
}
class Test {
int a;
int b;
}
int a;
int b;
void setData() {
super.a=10;
super.b=20;
a=30;
b=40;
}
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
149 | P a g e
void display() {
System.out.println ( “ Super class : a = “+super.a+” b = “ +super.b );
System.out.println ( “ Sub class : a = “+a+” b = “ +b );
}
}
t1.setData();
t1.display();
}
}
Directly we can't access super class data members using object, if super class and sub class has same
data members.
class Person {
int id;
int age ;
char sex;
void setData() {
pid=1001;
age = 25;
sex = 'M”
}
void display() {
System.out.println ( “ Id : “ +pid );
System.out.println ( “ Age : “+age);
System.out.println ( “Sex : “ +sex);
}
}
float salary;
void setData() {
super.setData();
salary = 20000.0f
}
Durga Soft
#202, 2ndFloor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
150 | P a g e
void display() {
super.display();
System.out.println ( “ salary : “+sal );
}
}
e1.setData();
e1.display();
}
}
Private members can be accessed in the same class only . Can not be accessed from sub / child class.
private int a;
private int b;
b=y;
}
Durga Soft
#202, 2ndFloor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
151 | P a g e
private int a;
private int b;
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
152 | P a g e
super.display();
Durga Soft
#202, 2ndFloor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
153 | P a g e
int c;
int d;
int i;
int j;
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
154 | P a g e
super.display();
System.out.println(i+"\t"+j);
}
t.setData(10, 20);
t.display();
System.out.println("===============");
t.setData(1, 2, 3, 4);
t.display();
System.out.println("===============");
t.display();
}
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
155 | P a g e
Hierarchial Inheritance:
eg:
package com.nrit.mnrao.hierarchial;
public void setData(int pid, String name, String gender, int age) {
this.pid = pid;
this.name = name;
this.gender = gender;
this.age = age;
}
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
156 | P a g e
package com.nrit.mnrao.hierarchial;
public void setData(int pid, String name, String gender, int age, String course, double
feePaid, double feeDue, char grade) {
this.course = course;
this.feePaid = feePaid;
this.feeDue = feeDue;
this.grade = grade;
package com.nrit.mnrao.hierarchial;
String dept;
double salary;
String desg;
public void setData(int pid, String name, String gender, int age, String dept, double salary,
String desg) {
setData(pid, name, gender, age);
this.dept = dept;
this.salary = salary;
this.desg = desg;
}
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
157 | P a g e
package com.nrit.mnrao.hierarchial;
student.display();
employee.display();
if method names are different then we can call from main method by using object.
Constructors invokes from bottom to top BUT executes from top to bottom.
Default constructors are invoked automatically ( implicitly )
public TestOne()
{
System.out.println ("Test One");
}
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
158 | P a g e
public TestTwo()
{
System.out.println ("Test Two");
}
int a;
int b;
public Test()
{
a=0;
b=0;
}
Durga Soft
#202, 2ndFloor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
159 | P a g e
int c;
int d;
public TestOne()
{
c=0;
d=0;
}
}
public void display()
{
super.display();
System.out.println(c+"\t"+d);
}
}
int i;
int j;
public TestTwo()
{
i=0;
j=0;
}
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
160 | P a g e
t2.display();
}
}
The statement, which makes a call to parent class constructor must be a first statement in the child
class constructor.
public TestOne()
{
c=0;
d=0;
}
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
161 | P a g e
Access Specifiers
It defines scope of classes and its members.
These are
public, protected, default and private.
Descending order is
Declaration:
Outside the Java From other Same package Within the same
application world packages ( sub class) class
( sub class )
public Yes Yes Yes Yes
protected No Yes Yes Yes
default No No Yes Yes
private No No No Yes
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
162 | P a g e
Durga Soft
#202,2nd Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
163 | P a g e
Access Modifiers
It defines behaviour of classes and it’s members.
1) static
2) final
3) abstract
4) synchronize.
5) transient.
6) native
7) volatile
Static:
2) methods
3) static blocks.
5) static import
Static import ;
if any class importing as static, then it's static members can be accessed directly with out using class
name .
eg:
package com.durga.mnrao.x;
Durga Soft
#202, 2ndFloor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
164 | P a g e
package com.durga.mnrao.y;
System.out.println(a); valid
System.out.println(b); valid
display(); valid
Eg:
if System imported as static then, it's static members such as in, out and err can be accessed directly
with out using System class refernce.
package com.durga.mnrao.y;
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
165 | P a g e
import java.util.Scanner;
out.println("hello world");
out.println("hello java");
final :
1) local variables
2) class data members ( instance variable / class variable )
3) methods
4) classes.
abstract:
Final:
}
eg2:
Durga Soft
#202, 2ndFloor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
166 | P a g e
{
final int A;
final data member can be initialized at the class level or inside the constructor or initialize block.
Class Level:
Below is not valid one. Since method may be invoking many times.
final int A;
A=10;
}
}
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
167 | P a g e
{
final int A;
{
A=20; // valid since initialize block invoking only once.
}
}
eg1:
public class Sample
{
final int A;
public Sample()
{
A=10;
}
}
eg2:
public class Sample
{
final int A=10;
public Sample()
{
A=20;// Invalid as final data member takes only one time assignment.
}
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
168 | P a g e
{
A=10; // not valid
}
public Sample()
{
A=10; // not valid
}
}
Eg:
{
A=10;//valid
}
public Sample()
{
A=20;//Invalid as final data member takes only one time assignment.
}
final int A;
{
A=10;
}
{
A=20;// Invalid
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
169 | P a g e
}
}
Purpose of constructor is used to initialize variable data members ( its value can be changed )
Purpose of initiailize block is used to initialize final data members ( its value can not be changed )
Purpose of multiple initialize blocks is used to segregate the constants, in the scenario where Java
application is connecting to different external servers ( resources ).
int x;
int y;
In the above case, every object contains final data member A ( read only but not modify ).
For every instance separate copy creates.
int x;
int y;
In the above case, final and static data member A is not a part of object, it is a separate copy, it can be
shared by all objects of the class ( only read can not modify ).
1) Class level
2) Using static block.
1) Class Level
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
170 | P a g e
static
{
A=20;
}
}
static
{
A=20;// invalid as final data member does not take second time assignment.
}
}
Purpose of static block is used to initiailize final and static data memebrs.
Purpose of multiple static blocks are used to segregate the static constants, in the scenario where
Java application is connecting to different external servers ( resources ).
method as final:
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
171 | P a g e
}
}
Static method can override but it should be static in both classe, parent as well as child.
Static and final should not override , both are static and final in both classe, parent as well as
child.
class as final :
it prevents from the inheritance. Final class members can not be inherited into child class.
Eg:
Abstract :
It is an access modifier
1) classes
2) methods
Abstract class:
Durga Soft
#202,2nd Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
172 | P a g e
}
}
Abstract class does not allow to create insatance. Abstract class can have only abstract methods (or)
all concrete mothods (or) it can have both.
Concrete class allows to create instance. Concreate class contains all concrete methods
abstract class does not allow to create an object but allows to declare reference .
purpose of abstract class reference variable is to refer to child class instance (used in polymorphism )
Eg:
Sample s1 = new Sample(); ---> Invalid, does not allow to create an object
Method as an abstract :
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
173 | P a g e
1) abstract method:
declaration.
2) concrete method
if class contains atleast one abstract method, then class becomes as an abstract class.
}
}
}
}
Abstract method should be implemented in the child class, otherwise child class also become as an
abstract class.
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
174 | P a g e
Eg:
Below abstract class contains all concrete methods. It is valid one.
}
}
Durga Soft
#202, 2ndFloor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
175 | P a g e
Interface
interface is similar to class
Declaration:
@Override
public void show()
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
176 | P a g e
}
}
all methods of an interface should be implemented in the child class, otherwise child class becomes
as an abstract class.
Eg:
public interface MyInterface {
int x;
int y;
@Override
public void setData(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public void display() {
System.out.println(x+"\t"+y);
System.out.println(A+"\t"+B);
}
}
s1.setData(10, 20);
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
177 | P a g e
s2.setData(30, 40);
s1.display();
s2.display();
}
Interface data members are Global data, hence these can be used any where in the project by
importing interface.
Eg:
package com.nrit.mnrao.test;
package com.nrit.mnrao.test1;
import com.nrit.mnrao.test.MyInterface;
Eg:
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
178 | P a g e
@Override
public void show() {
// TODO Auto-generated method stub
@Override
public void display() {
// TODO Auto-generated method stub
}
public class Test
{
public static void main(String[] args) {
i1.show();
i1.display();
}
}
Another eg:
i1.show();
i1.display();
i1.setData();// invalid since it is not member of MyInterface.
}
}
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
179 | P a g e
}
@Override
public void show()
{
System.out.println ("show");
System.out.println (A);
System.out.println (B);
}
}
public class Test
{
public static void main(String[] args)
{
MyInterface i1 = new Sample();
i1.display();
i1.show();
}
}
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
180 | P a g e
A class can implement multiple interfaces but extends only one class.
Eg:
}
public interface MyInter3 {
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
181 | P a g e
System.out.println(MyInter1.A);//valid
System.out.println(MyInter2.A); //valid
System.out.println(MyInter3.A); //valid
}
}
Adapter class:
Eg:
Durga Soft
#202, 2ndFloor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
182 | P a g e
@Override
public void m1() {
// TODO Auto-generated method stub
}
@Override
public void m2() {
// TODO Auto-generated method stub
}
@Override
public void m3() {
// TODO Auto-generated method stub
}
@Override
public void m4() {
// TODO Auto-generated method stub
@Override
public void m5() {
// TODO Auto-generated method stub
}
@Override
public void m6() {
// TODO Auto-generated method stub
@Override
public void m7() {
// TODO Auto-generated method stub
}
@Override
public void m8() {
// TODO Auto-generated method stub
}
@Override
public void m9() {
// TODO Auto-generated method stub
}
@Override
public void m10() {
// TODO Auto-generated method stub
}
Durga Soft
#202,2nd Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
183 | P a g e
Below A , B and C are actual classes to implement different services for different usage.
@Override
public void m1() {
// TODO Auto-generated method stub
@Override
public void m2() {
// TODO Auto-generated method stub
}
}
@Override
public void m3() {
// TODO Auto-generated method stub
@Override
public void m4() {
// TODO Auto-generated method stub
}
}
public class C extends Temp {
@Override
public void m5() {
// TODO Auto-generated method stub
@Override
public void m6() {
// TODO Auto-generated method stub
Durga Soft
#202, 2ndFloor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
184 | P a g e
Polymorphism
Poly --> many
Morphism --> forms
def:
same method, behaving differently for different purpose is called as polymorphism.
@Override
public void draw() {
System.out.println ("Square");
}
}
@Override
public void draw() {
System.out.println ("Triangle");
}
}
public class PolyTest
{
public static void main(String[] args)
{
Picture p1;
p1=new Rectangle();
Durga Soft
#202, 2ndFloor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
185 | P a g e
p1.draw();
p1=new Triangle();
p1.draw();
p1=new Square();
p1.draw();
}
}
Another way of main()
dispaly(new Triangle());
dispaly(new Square());
}
Another example:
package com.visix;
CitiBank.java:
package com.visix;
HdfcBank.java:
Durga Soft
#202, 2ndFloor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
186 | P a g e
package com.visix;
System.out.println (bank.getRateOfInterest());
System.out.println (bank.getRateOfInterest());
}
}
Interview Questions
Ans: abstract class, partially implented class, if class contains atleast one abstract method, then class
becomes abstract,
abstract class doesn't allow to create object.
Ans: Yes we can create an abstract class by using abstract keyword before class name even if it
doesn’t have any abstract method. However, if a class has even one abstract method, it must be
declared as abstract otherwise it will give an error.
Ans: The primary difference between an abstract class and interface is that an interface can only
possess declaration of public static methods with no concrete implementation while an abstract class
can have members with any access specifiers (public, private etc) with or without concrete
implementation.
Another key difference in the use of abstract classes and interfaces is that a class which implements
an interface must implement all the methods of the interface while a class which inherits from an
Durga Soft
#202, 2ndFloor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
187 | P a g e
abstract class doesn’t require implementation of all the methods of its super class.
A class can implement multiple interfaces but it can extend only one abstract class.
Ans: In java, when a package is imported, its sub-packages aren’t imported and developer needs to
import them separately if required.
For example, if a developer imports a package university.*, all classes in the package named
university are loaded but no classes from the sub-package are loaded. To load the classes from its
sub-package ( say department), developer has to import it explicitly as follows:
Import university.department.*
Ans: In java, main method must be public static in order to run any application correctly. If main
method is declared as private, developer won’t get any compilation error however, it will not get
executed and will give a runtime error.
Ans: We cannot override static methods. Static methods belong to a class and not to individual
objects and are resolved at the time of compilation (not at runtime).Even if we try to override static
method,we will not get an complitaion error,nor the impact of overriding when running the code.
7. Can a class be a super class and a sub-class at the same time? Give example.
Ans: If there is a hierarchy of inheritance used, a class can be a super class for another class and a
sub-class for another one at the same time.
8. There are two classes named classA and classB. Both classes are in the same package. Can a
private member of classA can be accessed by an object of classB?
Ans: Private members of a class aren’t accessible outside the scope of that class and any other class
even in the same package can’t access them.
Ans: Key benefit of using inheritance is reusability of code as inheritance enables sub-classes to
reuse the code of its super class. Polymorphism (Extensibility ) is another great benefit which allow
new functionality to be introduced without effecting existing derived classes.
Ans: There are no pointers in Java. So we can’t use concept of pointers in Java.
11.How can we restrict inheritance for a class so that no class can be inherited from it?
Ans: If we want a class not to be extended further by any class, we can use the keyword Final with
Durga Soft
#202, 2ndFloor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
188 | P a g e
Outside the Java From other Same package Within the same
world packages ( sub class) class
( sub class )
public Yes Yes Yes Yes
protected No Yes Yes Yes
default No No Yes Yes
private No No No Yes
When we have more than one method with same name in a single class but the arguments are
different, then it is called as method overloading.
Overriding concept comes in picture with inheritance when we have two methods with same
signature, one in parent class and another in child class. We can use @Override annotation in the
child class overridden method to make sure if parent class method is changed, so as child class.
final keyword is used with Class to make sure no other class can extend it, for example String class is
final and we can’t extend it.
We can use final keyword with methods to make sure child classes can’t override it.
final keyword can be used with variables to make sure that it can be assigned only once. However
the state of the variable can be changed, for example we can assign a final variable to an object only
once but the object variables can change later on.
15.What is an interface?
Interfaces are core part of java programming language and used a lot not only in JDK but also java
design patterns, most of the frameworks and tools. Interfaces provide a way to achieve abstraction in
java and used to define the contract for the subclasses to implement.
Interfaces are good for starting point to define Type and create top level hierarchy in our code. Since
a java class can implements multiple interfaces, it’s better to use interfaces as super class in most of
the cases
Durga Soft
#202, 2ndFloor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
189 | P a g e
Abstract classes are used in java to create a class with some default method implementation for
subclasses. An abstract class can have abstract method without body and it can have methods with
implementation also.
abstract keyword is used to create a abstract class. Abstract classes can’t be instantiated and mostly
used to provide base for sub-classes to extend and implement the abstract methods and override or
use the implemented methods in abstract class.
abstract keyword is used to create abstract class whereas interface is the keyword for interfaces.
A class can extend only one abstract class but it can implement multiple interfaces.
We can run abstract class if it has main() method whereas we can’t run an interface.
Interfaces don’t implement another interface, they extend it. Since interfaces can’t have method
implementations, there is no issue of diamond problem. That’s why we have multiple inheritance in
interfaces i.e an interface can extend multiple interfaces.
We can use instanceof keyword to check if an object belongs to a class or not. We should avoid it’s
usage as much as possible. Sample usage is:
Durga Soft
#202, 2ndFloor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
190 | P a g e
This is a very confusing question, we know that object variables contain reference to the Objects in
heap space. When we invoke any method, a copy of these variables is passed and gets stored in the
stack memory of the method.
Passing object is call by reference where as passing variable is a call by value.
21.What is Polymorphism?
Polymorphism is the ability of an object to take on many forms. The most common use of
polymorphism in OOP occurs when a parent class reference is used to refer to a child class object.
Binding refers to the linking of a procedure call to the code to be executed in response to the call.
Dynamic binding means that the code associated with a given procedure call is not known until the
time of the call at run-time.
You can’t instantiate an interface directly, but you can instantiate a class that implements an
interface.
Interfaces may have member variables, but these are implicitly public, static, and final- in other
words, interfaces can declare only constants, not instance variables that are available to all
implementations and may be used as key references for method arguments for example.
An abstract class can never be instantiated. Its sole purpose is to be extended (subclassed).
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
191 | P a g e
29.When should I use abstract classes and when should I use interfaces?
If various implementations are of the same kind and use common behavior or status then abstract
class is better to use.
When you want to provide a generalized form of abstraction and leave the implementation task
with the inheriting subclass.
Abstract classes are an excellent way to create planned inheritance hierarchies. They're also a good
choice for nonleaf classes in class hierarchies.
is bound with object and static gets memory in class area and instance gets memory in heap.
36) Can we define private and protected modifiers for variables in interfaces?
No, they are implicitly public.
Strings
String is a class from java.lang package.
Java String provides a lot of concepts that can be performed on a string such as compare, concat,
equals, split, length, replace, compareTo, intern, substring etc.
Eg:
Different ways :
String s1;
s1="hello";
=================
String s2="hello";
===================
String s3;
s3=new String("hello");
========================
String s4= new String ("hello");
========================
String s5=s4;
=====================
String s6 = new String( s4);
String s1=null; string reference is null, it can not be used, it throws NullPointerException.
String s2= new String(); s2 is reference String object, which contains nothing, empty object ( zero
no of chars )
Durga Soft
#202,2nd Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
193 | P a g e
char [] ch ={'n','r','i','t'};
System.out.println(s1);
The java String is immutable i.e. it cannot be changed but a new instance is created.
For mutable class, you can use StringBuffer and StringBuilder class.
By string literal
By new keyword
1) String Literal
String s="welcome";
Each time you create a string literal, the JVM checks the string constant pool first. If the string
already exists in the pool, a reference to the pooled instance is returned. If string doesn't exist in the
pool, a new string instance is created and placed in the pool. For example:
String s1="Welcome";
String s2="Welcome";//will not create new instance
In the above example only one object will be created. Firstly JVM will not find any string object
with the value "Welcome" in string constant pool, so it will create a new object. After that it will find
the string with the value "Welcome" in the pool, it will not create new object but will return the
reference to the same instance.
Note: String objects are stored in a special memory area known as string constant pool.
To make Java more memory efficient (because no new objects are created if it exists already in string
constant pool).
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
194 | P a g e
2) By new keyword
In such case, JVM will create a new string object in normal(non pool) heap memory and the literal
"Welcome" will be placed in the string constant pool. The variable s will refer to the object in
heap(non pool).
char ch[]={'s','t','r','i','n','g','s'};
String s2=new String(ch);//converting char array to string
System.out.println (s2);
System.out.println (s3);
System.out.println (s4);
}
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
195 | P a g e
values.
1 char charAt(int index) returns char value for the particular index
2 int length() returns string length
5 String substring(int beginIndex)
6 String substring(int beginIndex, returns substring for given begin index and end index
int endIndex)
7 boolean contains(CharSequence s) returns true or false after matching the sequence of
char value
10 boolean equals(Object another) checks the equality of string with object
11 boolean isEmpty() checks if string is empty
13 String replace(char old, char new) replaces all occurrences of specified char value
14 String replace(CharSequence old, replaces all occurrences of specified CharSequence
CharSequence new)
15 String trim() returns trimmed string omitting leading and trailing
spaces
16 String [] split(String regex) returns splitted string matching regex
19 int indexOf(int ch) returns specified char value index
20 int indexOf(int ch, int fromIndex) returns specified char value index starting with given
index
21 int indexOf(String substring) returns specified substring index
22 int indexOf(String substring, int returns specified substring index starting with given
fromIndex) index
23 String toLowerCase() returns string in lowercase.
25 String toUpperCase() returns string in uppercase
1. charAt()
String s1="hello";
char ch = s1.charAt(0);
System.out.println(ch);
ch = s1.charAt(5);
// throws StringIndexOutOfBoundsException
2. length()
String s1="hello";
int len = s1.length();
System.out.println(len);
3. getBytes()
String s1="hello";
4. indexOf()
String s1="hello";
int index = s1.indexOf('l');
System.out.println(index);
String s1="";
if(s1.isEmpty())
{
System.out.println("yes");
}
else
{
System.out.println("No empty");
}
String s1=null;
if(s1.isEmpty()) // NullPointerException
{
System.out.println("yes");
}
else
{
System.out.println("No empty");
}
6.replace()
7. toUpperCase()
String s1="hello";
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
197 | P a g e
String s2 = s1.toUpperCase();
System.out.println(s1);
System.out.println(s2);
For every attempt to modify, it will create new location and return reference to new location.
8.toLowerCase()
String s1="HeLlO12345";
String s2 = s1.toLowerCase();
System.out.println(s1);
System.out.println(s2);
9.trim()
String s1=" hello ";
System.out.println(s1.length()); // 7
String s2 = s1.trim();
System.out.println(s1.length()); // 7
System.out.println(s2.length()); // 5
10. contains()
System.out.println(index);
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
198 | P a g e
System.out.println(index);
By equals() method
By = = operator
By compareTo() method
The String equals() method compares the original content of the string. It compares values of string
for equality. String class provides two methods:
public boolean equals(Object another) compares this string to the specified object.
public boolean equalsIgnoreCase(String another) compares this String to another string, ignoring
case.
if(s1.equals(s2))
{
System.out.println ("both are equal");
}
else {
System.out.println ("not equal");
}
}
}
o/p :
Durga Soft
#202, 2ndFloor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
199 | P a g e
if(s1.equals(s2))
{
System.out.println ("both are equal");
}
else
{
System.out.println ("not equal");
}
}
}
O/P ;
not equal
if(s1.equalsIgnoreCase(s2))
{
System.out.println ("both are equal");
}
else
{
System.out.println ("not equal");
}
}
}
Eg:
Program to validate userid and password.
Durga Soft
#202, 2ndFloor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
200 | P a g e
import java.util.Scanner;
if(s1==s2)
{
System.out.println("same location");
}
else
{
System.out.println("different location");
}
}
}
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
201 | P a g e
String s1 = "hello";
if (s1 == s2) {
System.out.println("same location");
} else {
System.out.println("different location");
}
}
If “hello” already exist in the string pool, then only one creates inside the heap memory.
If “hello” does not exist in the string pool, then one object with “hello” palcing inside the string
pool and another is created inside the heap memory.
if(s1==s2)
{
System.out.println ("Same location");
}
else
{
System.out.println ("Different location");
}
}
}
o/p; Same location
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
202 | P a g e
String s1 = "hello";
o/p :
different location
if ("hello" == "hello") {
System.out.println("same location");
} else {
System.out.println("different location");
}
}
}
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
203 | P a g e
String Pool is possible only because String is immutable in Java and it’s implementation of String
interning concept. String pool is also example of Flyweight design pattern.
String pool helps in saving a lot of space for Java Runtime although it takes more time to create the
String.
When we use double quotes to create a String, it first looks for String with same value in the String
pool, if found it just returns the reference else it creates a new String in the pool and then returns the
reference.
However using new operator, we force String class to create a new String object in heap space. We
can use intern() method to put it into the pool or refer to other String object from string pool having
same value.
/**
* Java String Pool example
* @param args
*/
public static void main(String[] args) {
String s1 = "Cat";
String s2 = "Cat";
String s3 = new String("Cat");
System.out.println("s1 == s2 :"+(s1==s2));
System.out.println("s1 == s3 :"+(s1==s3));
}
O/P:
s1 == s2 :true
s1 == s3 :false
Durga Soft
#202, 2ndFloor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
204 | P a g e
In above statement, either 1 or 2 string will be created. If there is already a string literal “Cat” in the
pool, then only one string “str” will be created in the pool. If there is no string literal “Cat” in the
pool, then it will be first created in the pool and then in the heap space, so total 2 string objects will
be created.
if(s1==s2)
{
System.out.println ("Same location");
}
else
{
System.out.println ("Different location");
}
}
}
if(s1==s2)
{
System.out.println ("Same location");
}
else
{
System.out.println ("Different location");
}
}
}
Durga Soft
#202, 2ndFloor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
205 | P a g e
if(s1==s2)
{
System.out.println ("Same location");
}
else
{
System.out.println ("Different location");
}
}
}
The String compareTo() method compares values lexicographically and returns an integer value that
describes if first string is less than, equal to or greater than second string.
It compares ASCII value of the String.
Suppose s1 and s2 are two string variables.
if(s1.compareTo(s2)==0)
{
System.out.println ("Same");
}
else
Durga Soft
#202, 2ndFloor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
206 | P a g e
{
System.out.println ("Not Same");
}
}
}
O/P: Same
if(s1.compareTo(s2)>0)
{
System.out.println ("S1 > S2");
}
else
{
System.out.println ("S2 > S1");
}
}
}
O/P: S1 > S2
if(s1.compareToIgnoreCase(s2)==0)
{
System.out.println ("Same");
}
else
{
System.out.println ("Not Same");
}
O/P: same
Durga Soft
#202, 2ndFloor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
207 | P a g e
}
}
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
208 | P a g e
System.out.println (s2);
String s4 = s2+"\t"+s3;
System.out.println (s4);
}
}
O/P:
hellojava
hellojava world
The string replace() method replaces all occurrence of first sequence of character with second
sequence of character.
System.out.println (s1);
System.out.println (replaceString);
}
}
Output:
Java is a programming language. Java is a platform. Java is an Island.
Kava is a programming language. Kava is a platform. Kava is an Island.
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
209 | P a g e
String value can not be changed for every attempt on the String it creates new location.
System.out.println (replaceString);
}
}
Output:
Java is a programming language. Java is a platform. Java is an Island.
Kava is a programming language. Kava is a platform. Kava is an Island.
O/P;
java
linux
unix
hadoop
html
public class Test {
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
210 | P a g e
System.out.println(fields[0]+"\t"+fields[1]+"\t"+fields[4]);
}
}
O/p:
package com.nrit.mnrao.test;
}
// initialization
public Sample(int id, String name)
{
this.id =id;
this.name =name;
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
211 | P a g e
//Cloning s2 from s1
Sample s2 = s1.newInstance();
if(s1!=s2)
{
System.out.println("cloned");
}
else
{
System.out.println("cloning failed");
}
if(s1!=s3)
{
System.out.println("Copy created");
}
else
{
System.out.println("copy failed");
}
System.out.println(s1.getId()+"\t"+s1.getName());
System.out.println(s2.getId()+"\t"+s2.getName());
System.out.println(s3.getId()+"\t"+s3.getName());
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
212 | P a g e
If String is not immutable then it would cause severe security threat to the application. For example,
database username, password are passed as String to get database connection and in socket
programming host and port details passed as String. Since String is immutable it’s value can’t be
changed otherwise any hacker could change the referenced value to cause security issues in the
application.
Since String is immutable, it is safe for multithreading and a single String instance can be shared
across different threads. This avoid the usage of synchronization for thread safety, Strings are
implicitly thread safe.
Strings are used in java classloader and immutability provides security that correct class is getting
loaded by Classloader. For example, think of an instance where you are trying to load
java.sql.Connection class but the referenced value is changed to myhacked.Connection class that can
do unwanted things to your database.
StringBuffer
It is a class from java.lang package
Durga Soft
#202, 2ndFloor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
213 | P a g e
Java StringBuffer class is used to create mutable (modifiable) string. The StringBuffer class in java is
same as String class except, it is mutable i.e. it can be changed.
Note: Java StringBuffer class is thread-safe i.e. multiple threads cannot access it
simultaneously. So it is safe and will result in an order.
StringBuffer() --> creates an empty string buffer with the initial capacity of 16 bytes.
StringBuffer(int capacity)--> creates an empty string buffer with the specified capacity as length.
is used to insert the specified string with this string at the specified position. The insert() method is
overloaded like insert(int, char), insert(int, boolean), insert(int, int), insert(int, float), insert(int,
double) etc.
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
214 | P a g e
is used to return the length of the string i.e. total number of characters.
is used to return the substring from the specified beginIndex and endIndex.
Eg:
public class Test {
sb.append(record1);
sb.append("\n");
sb.append(record2);
sb.append("\n");
sb.append(record3);
sb.append("\n");
sb.append(record4);
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
215 | P a g e
sb.append("1001:Sri Ram:5000.0:dev\n");
sb.append("1002:Manoj:6000.0:admin\n");
sb.append("1003:Anusha:6500.0:testing\n");
sb.append("1004:prasad:5500.0:dev\n");
sb.append("1005:vinay:3500.0:finance\n");
sb.append("1006:mithun:5500.0:admin\n");
sb.append("1007:thirumala:8500.0:dev");
Ans: String is not a primitive data type in java. When a string is created in java, it’s actually an
object of Java.Lang.String class that gets created. After creation of this string object, all built-in
methods of String class can be used on the string object.
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
216 | P a g e
Ans: In java, string objects are called immutable as once value has been assigned to a string, it can’t
be changed and if changed, a new object is created.
3. When a lot of changes are required in data, which one should be a preference to be used? String or
StringBuffer?
Ans: Since StringBuffers are dynamic in nature and we can change the values of StringBuffer objects
unlike String which is immutable, it’s always a good choice to use StringBuffer when data is being
changed too much. If we use String in such a case, for every data change a new String object will be
created which will be an extra overhead.
Ans: Primitive data types like int can be handled as objects by the use of their respective wrapper
classes. For example, Integer is a wrapper class for primitive data type int. We can apply different
methods to a wrapper class, just like any other object.
5. Can we use a default constructor of a class even if an explicit constructor is defined?
Ans: Java provides a default no argument constructor if no explicit constructor is defined in a Java
class. But if an explicit constructor has been defined, default constructor can’t be invoked and
developer can use only those constructors which are defined in the class.
Java wrapper classes are the Object representation of eight primitive types in java. All the wrapper
classes in java are immutable and final. Java 5 autoboxing and unboxing allows easy conversion
between primitive types and their corresponding wrapper classes.
As we know, for all the primitive types we have wrapper classes such as Integer, Long etc that
provides some additional methods.
System class is final so that we can’t subclass and override it’s behavior through inheritance. System
class doesn’t provide any public constructors, so we can’t instantiate this class and that’s why all of
it’s methods are static.
Some of the utility methods of System class are for array copy, get current time, reading environment
variables.
Durga Soft
#202, 2ndFloor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
217 | P a g e
11) What is the basic difference between string and stringbuffer object?
String is an immutable object. StringBuffer is a mutable object.
StringTokenizer
The java.util.StringTokenizer class allows an application to break a string into tokens.
This class is a legacy class that is retained for compatibility reasons although its use is
discouraged in new code.
Durga Soft
#202, 2ndFloor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
218 | P a g e
Its methods do not distinguish among identifiers, numbers, and quoted strings.
This class methods do not even recognize and skip comments.
Class declaration
Following is the declaration for java.util.StringTokenizer class:
Class constructors
StringTokenizer(String str)
int countTokens()
This method calculates the number of times that this tokenizer's nextToken method can be called
before it generates an exception.
“java:oracle:linux:unix:sql”
boolean hasMoreElements()
boolean hasMoreTokens()
This method tests if there are more tokens available from this tokenizer's string.
Object nextElement()
This method returns the same value as the nextToken method, except that its declared return value is
Object rather than String.
String nextToken()
This method returns the next token from this string tokenizer.
This method returns the next token in this string tokenizer's string.
Durga Soft
#202, 2ndFloor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
219 | P a g e
import java.util.StringTokenizer;
StringTokenizer st1 = new StringTokenizer("Hadoop Java Html Oracle Linux", " ");
while (st1.hasMoreTokens())
{
System.out.println (st1.nextToken());
}
while (st2.hasMoreTokens())
{
System.out.println (st2.nextToken());
}
}
}
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
220 | P a g e
2)Basic to Object
3)Object to Basic
4) Object to Object
5) Sting to Basic
6) Basic to String
These are
1) implicit casting:
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
221 | P a g e
eg1:
byte b=10;
short s = b ; --> valid
eg2:
int a=10;
long b=a; --> valid
eg3:
float a=10.5f;
double b=a; --> valid
2) Explicit casting:
Short a=10;
byte b = (byte ) a ; --> it is valid
short a=130;
byte b = (byte ) a ; --> it compiles but at run time loss of data. It results in unexpected data
( i.e leads to bugs )
here value of b is -126 .
hence explicit type casting is recommended is only for constants not for variables.
float a= 10.5 ; --> invalid, since in java real numbers by default treats as double.
float a= 10.5f; --> valid
default,
integer data ( number ) is a int data type not a short and byte.
Real numbers are treated as double type.
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
222 | P a g e
3) int + int = int ( compiles ) but at runtime there is chance of data flow.
Recommended one is ( int+int = long )
4) long + long = long
5) char + char = int.
for every basic type java provides Object wrapper class to convert basic type to Object type.
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
223 | P a g e
Note: All the above wrapper classes are from java.lang package.
Wrapper classes are immutable and final.
eg1:
int a=10;
eg2:
double b=100.50;
Object Wrapper classes provides xValue() to convert from Object to basic type.
Eg:
for integer x is int.
For float x is float
eg1:
eg2:
double b = d1.doubleValue();
Durga Soft
#202, 2ndFloor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
224 | P a g e
Auto boxing:
it is a conversion of data from basic to Object type:
eg:
Integer i1 = 10;// directly can be assigned.
Auto unboxing:
4) Object to Object :
1) Up casting
2) Down casting
1) Up casting :
Eg:
Below is the parent.
package com.nrit.mnrao.test;
Child class:
package com.nrit.mnrao.test;
Durga Soft
#202, 2ndFloor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
225 | P a g e
System.out.println("Rectangle");
}
}
2) Down Casting :
Object class:
Eg:;
Source code.
Sample.java as below.
Aftfter compilation
Sample.class contains following code.
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
226 | P a g e
All the members of Objet gets inherited into Sample class. Hence Sample class object contains
Object class members as well it’s own members.
System.out.println(name);
O/P :
Sample.
System.out.println(s1);
Here println() expecting string, hence it makes to toString(), if toString() is available in the child
class, then it makes call to child class method, if not avaialable then it makes a call to Obeject class
toString() method.
package com.nrit.mnrao.test;
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
227 | P a g e
public Sample() {
id = 0;
name = null;
}
@Override
public String toString() {
return "Sample [id=" + id + ", name=" + name + "]";
}
}
package com.nrit.mnrao.test;
System.out.println(s1);
}
}
Note: toString() works only on the objects but not with basic data type.
System.out.println(str);
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
228 | P a g e
{
System.out.println("invalid runtime instance, expected for String type ");
}
wait() to put the thread into waiting state for shared resources.
Eg1:
String str="101";
Eg2:
String str="100.50";
float f = Float.parseFloat(str);
package com.nrit.mnrao.test;
import java.util.Scanner;
System.out.println("Enter EMPNO:");
inputData = sc.next();
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
229 | P a g e
System.out.println(eno+"\t"+name+"\t"+salary+"\t"+dept);
}
}
O/P;
Enter EMPNO:
1001
Enter name
abc
Enter Salary
5000
Enter Dept
dev
1001 abc 5000.0 dev
package com.nrit.mnrao.test;
}
6)Basic ( any type ) to String type:
=========================
String class provides static overloaded valueOf() method to convert any basic type of data into String
type.
Eg1:
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
230 | P a g e
int a=125;
Eg2:
float a=30.56f;
System.out.println(str);
As Object class is a default parent for every class it can refer to any object.
Exception Handling
before going to learn Exceptions, we should clear about, error, exception, bug and defect
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
231 | P a g e
Bug : It is an unexpected value at runtime. Even bug raises application never terminates
abnormally. It can be fixed.
Defect : It can't be fixed. Some features may not be provided by the application software. It is
manufacturing defect.
The exception handling in java is one of the powerful mechanism to handle the runtime errors so that
normal flow of the application can be maintained.
What is an exception
In java, exception is an event that disrupts the normal flow of the program. It is an object which is
thrown at runtime.
Exception Handling is a mechanism to handle runtime errors such as ClassNotFound, IO, SQL,
Remote etc.
The core advantage of exception handling is to maintain the normal flow of the application.
Exception normally disrupts the normal flow of the application that is why we use exception
handling.
statement 1;
statement 2;
statement 3;
statement 4;
statement 5;//exception occurs
statement 6;
statement 7;
statement 8;
statement 9;
statement 10;
Suppose there are 10 statements in your program and there occurs an exception at statement
5, rest of the code will not be executed i.e. statement 6 to 10 will not run. If we perform exception
handling, rest of the exception will be executed. That is why we use exception handling in java.
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
232 | P a g e
There are given some scenarios where unchecked exceptions can occur. They are as follows:
1) Scenario where ArithmeticException occurs
int a= 50/0;//ArithmeticException
If we have null value in any variable, performing any operation by the variable occurs an
NullPointerException.
String s=null;
System.out.println (s.length());//NullPointerException
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
233 | P a g e
The wrong formatting of any value, may occur NumberFormatException. Suppose I have a string
variable that have characters, converting this variable into digit will occur NumberFormatException.
String s="10ab2”;
int i=Integer.parseInt(s);//NumberFormatException
If you are inserting any value in the wrong index, it would result ArrayIndexOutOfBoundsException
as shown below:
Java try-catch
Java try block is used to enclose the code that might throw an exception. It must be used within the
method.
try
{
------------------------;
-------------------------;
-------------------------; //code that may throw exception
-------------------------;
-------------------------;
}
catch(Exception_Type ref)
{
---------------------;
---------------------;
}
------------
------------
Example :
Durga Soft
#202, 2ndFloor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
234 | P a g e
{
public static void main( String [] args )
{
System.out.println ("Main Start");
try
{
System.out.println ("tray start");
int a=10;
int b;
int n=args.length;
b=a/n;
try
{
----------;
----------;
----------;
----------;
}
catch ( )
{
}
catch ( )
{
}
catch ( )
{
}
catch ( )
{
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
235 | P a g e
try {
int a = 10;
int n = args.length;
int b = a / n;
Durga Soft
#202,2nd Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
236 | P a g e
default catch :
catch (Exception e )
{
try
{
int a = 10;
int n = args.length;
int b = a / n;
System.out.println ("Result ; " + b);
System.out.println ("First args:" + args[0]);
System.out.println ("Second args:" + args[1]);
System.out.println ("Third args:" + args[2]);
System.out.println ("End of try");
}
catch (ArithmeticException e)
{
System.out.println ("devide by zero exception");
}
catch (NullPointerException e)
{
System.out.println ("Null Pointer Exception");
}
catch (Exception e )
{
System.out.println ("default exception");
}
Durga Soft
#202, 2ndFloor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
237 | P a g e
Since it is a parent of all Exception classes, it can hadle all kinds of exceptions.
package com.nrit.mnrao.test;
import java.util.Scanner;
System.out.println("Employee details");
Scanner sc = new Scanner(System.in);
int eno;
String empName;
double salary;
String deptName;
while(true)
{
try
{
System.out.println("Emp Num : ");
String inputData = sc.nextLine();
eno = Integer.parseInt(inputData);
break;
}
catch(NumberFormatException e)
{
System.out.println("Non numeric input data");
continue;
while(true)
{
try
{
System.out.println("Emp Salary : ");
String inputData = sc.nextLine();
salary = Double.parseDouble(inputData);
break;
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
238 | P a g e
}
catch(NumberFormatException e)
{
System.out.println("invalid salary ");
continue;
}
System.out.println(eno+"\t"+empName+"\t"+salary+"\t"+deptName);
sc.close();
}
}
Input :
Employee details
Emp Num :
1001
emp name
abc
Emp Salary :
5000
dept name
dev
output:
Your input details are
1001 abc 5000.0 dev
Input data
Employee details
Emp Num :
10ab10
Non numeric input data
Emp Num :
10x20
Non numeric input data
Emp Num :
1001
emp name
dev
Emp Salary :
Durga Soft
#202,2nd Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
239 | P a g e
5000,50
invalid salary
Emp Salary :
5000#50
invalid salary
Emp Salary :
5000.50
dept name
admin
Output:
Finally block contain certain statement to be executed wether terminated normally or abnormally.
These are compulsory statements. Mostly cleaning operations such as file closing, database
connection closing, tcp sockets closing and etc.
Durga Soft
#202,2nd Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
240 | P a g e
Case 1:
try
{
}
catch (Exception e)
{
// TODO: handle exception
}
finally
{
Case 2:
try
{
}
finally
{
try
{
finally
{
}
catch (Exception e)
{
// TODO: handle exception
}
Durga Soft
#202,2nd Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
241 | P a g e
catch (Exception e)
{
// TODO: handle exception
}
finally
{
Multiple catch blocks can be placed but multiple finally blocks are not valid.
Example :
try
{
System.out.println ("Try start");
int a = 10;
int n = args.length;
int b = a / n;
}
catch (ArithmeticException e)
{
}
catch (NumberFormatException e)
Durga Soft
#202,2nd Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
242 | P a g e
}
finally
{
System.out.println ("I am in finally");
}
Input :
Command line params are as below
hello java world
main start
Try start
b= 3
First param = hello
Second param = java
Third param = world
try end
I am in finally
main end
Input :
No command line params
main start
Try start
arithmetic
I am in finally
main end
Input :
Command line params are as below
hello java
main start
Durga Soft
#202, 2ndFloor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
243 | P a g e
Try start
b= 5
First param = hello
Second param = java
I am in finally
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
at com.nrit.mnrao.test.Test.main(Test.java:26)
Normal termination:
Any statements after finally block will also be executed.
Abnormal termination:
Any statements after finally block will not be executed.
The try block within a try block is known as nested try block in java.
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
244 | P a g e
Sometimes a situation may arise where a part of a block may cause one error and the entire block
itself may cause another error. In such cases, exception handlers have to be nested.
Syntax:
try
{
----------;
----------;
try
{
----------;
----------;
----------;
----------;
}
catch ( )
{
}
catch ( )
{
}
----------;
----------;
}
catch ( )
{
}
catch ( )
{
----------;
---------;
Cases:
Case 1:
No exception in the out try as well as inner try, then no catch block executes and program completed
till end, then terminates.
Case 2:
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
245 | P a g e
Checks for the outer catch, if matched then, that catch blocks executes, if not matched, then termiates
abnormally.
Case 3:
Checks for the inner catch, if matched then, that catch blocks executes, then goes to outer try ending
statements, then termiates normally.
If not matched with inner catch, then checks for outer catch blocks, if matched then, that catch
blocks executes, then termiates normally. if not matched, then termiates abnormally.
try
{
System.out.println ("outer try start");
int a=10;
int n=args.length;
int b = a/n;
System.out.println ("b="+b);
try
{
System.out.println ("Innner try start");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println ("Inner try array index exception ");
}
finally
{
System.out.println ("Inner try finally");
}
Durga Soft
#202, 2ndFloor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
246 | P a g e
finally
{
System.out.println ("outer try finally");
}
System.out.println ("main end");
}
}
try
{
System.out.println ("tray start");
int a=10;
int b;
int n=args.length;
b=a/n;
System.out.println (args[1]);
System.out.println (args[2]);
System.out.println (args[3]);
Durga Soft
#202, 2ndFloor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
247 | P a g e
catch(NullPointerException e)
{
//System.out.println ("Divide by zero error");
e.printStackTrace();
}
catch(ArrayIndexOutOfBoundsException e)
{
//System.out.println ("Divide by zero error");
e.printStackTrace();
}
catch(Exception e)
{
System.out.println ("default catch");
}
}
catch (Exception e ) // default catch
{
}
catch (NullPointerException e ) // compile time error
{
}
catch (ArrayIndexOutOfBoundsException e ) ) // compile time error
{
Note: If you don't handle exception, before terminating the program, JVM executes finally block(if
Durga Soft
#202,2nd Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
248 | P a g e
any).
Finally block in java can be used to put "cleanup" code such as closing a file, closing connection
etc.
Eg:
eg:
package com.nrit.mnrao.test;
try
{
System.out.println ("tray start");
int a=10;
int b;
int n=args.length;
if(n==0)
{
throw new ArithmeticException();
}
b=a/n;
Durga Soft
#202, 2ndFloor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
249 | P a g e
System.out.println ("b="+b);
catch(ArithmeticException e)
{
System.out.println(e.getMessage());
}
If exception instance created by JVM implicitly, then JVM will initialize instance with text message.
Then getMessage() returns text message initialized by the JVM.
In the above example, java developer, has created exception instance but not initialized with any text
message. Hence it retruns null value.
public SampleException()
{
message=null;;
}
Durga Soft
#202,2nd Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
250 | P a g e
try {
System.out.println ("try start");
int a = 10;
int n = args.length;
if (n == 0) {
throw new SampleException("Sample user defined exception");
}
int b = a / n;
2) Catch block takes the class type as the argument, which is extedns of Exception class.
Durga Soft
#202, 2ndFloor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
251 | P a g e
Types of Exception
There are mainly two types of exceptions: checked and unchecked where error is considered as
unchecked exception. The sun microsystem says there are three types of exceptions:
1) Exception
Checked Exception
Unchecked Exception
2) Error
All Exception classes, from other than java.lang package are checked exceptions.
2) Unchecked Exception
Unchecked exceptions are not checked at compile-time rather they are checked at runtime.
The classes that extends RuntimeException e.g. ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException etc.
All the Exception classes from java.lang package are Unchecked Exceptions
3) Error
Error is irrecoverable
e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.
Checked exceptions should handled at compile time. It can be handled by using try –catch or usng
throws clause.
try –catch is used to get exception message, where as throws clause is to suppress Exception at
compile time.
The Java throws keyword is used to declare an exception. It gives an information to the programmer
that there may occur an exception so it is better for the programmer to provide the exception
handling code so that normal flow can be maintained.
Exception Handling is mainly used to handle the checked exceptions. If there occurs any unchecked
exception such as NullPointerException, it is programmers fault that he is not performing check up
before the code being used.
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
252 | P a g e
System.out.println("Main Start");
System.out.println("tray start");
int a = 10;
int b;
int n = args.length;
if (n == 0) {
throw new SampleException("Sample error");
}
b = a / n;
System.out.println("b=" + b);
System.out.println("main end");
}
Another example
System.out.println("Main Start");
display(args);
System.out.println("main end");
}
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
253 | P a g e
int b;
int n = args.length;
if (n == 0) {
throw new SampleException("Sample error");
}
b = a / n;
System.out.println("b=" + b);
}
If called method is having throws clause, then calling methods also must have throws clause or it
should hadeld by using try-catch.
System.out.println("Main Start");
display(args);
System.out.println("main end");
}
System.out.println("Main Start");
display(args);
System.out.println("main end");
}
If called method has throws clause then, calling method also must have throws clause.
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
254 | P a g e
System.out.println("Main Start");
display(args);
System.out.println("main end");
}
if (n == 0) {
throw new SampleException("Sample error");
}
b = a / n;
System.out.println("b=" + b);
}
System.out.println("Main Start");
display(args);
System.out.println("main end");
}
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
255 | P a g e
System.out.println("tray start");
int a = 10;
int b;
int n = args.length;
b = a / n;
System.out.println("b=" + b);
}
catch(ArithmeticException e)
{
e.printStackTrace();
}
}
}
Rasing exception in the Called method and hadling inside the calling method.
System.out.println("Main Start");
try
{
display(args);
}
catch(ArithmeticException e)
{
e.printStackTrace();
}
System.out.println("main end");
}
Durga Soft
#202, 2ndFloor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
256 | P a g e
}
}
System.out.println("Main Start");
try
{
display(args);
}
catch(ArithmeticException e)
{
e.printStackTrace();
}
System.out.println("main end");
}
public static void display( String[] args)
{
try
{
System.out.println("tray start");
int a = 10;
int b;
int n = args.length;
b = a / n;
System.out.println("b=" + b);
}
catch(ArithmeticException e)
{
System.out.println("divide by zero error ");
}
}
Durga Soft
#202,2nd Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
257 | P a g e
System.out.println("Main Start");
try
{
System.out.println("tray start");
int a = 10;
int b;
int n = args.length;
b = a / n;
System.out.println("b=" + b);
}
catch(ArithmeticException e)
{
System.exit(0);
System.out.println("divide by zero error ");
System.out.println("main end");
}
There are many differences between throw and throws keywords. A list of differences between throw
and throws are given below:
throw throws
Java throw keyword is used to explicitly Java throws keyword is used to declare an
throw an exception. exception.
Throw key word is throw Checked Checked exception can be suppressed with
exceptions. throws.
Throw is followed by an instance. Throws is followed by class.
Throw is used within the method. Throws is used with the method signature.
We cannot throw multiple exceptions. We can declare multiple exceptions e.g.
public void method() throws
IOException,SQLException.
There are many differences between final, finally and finalize. A list of differences between final,
finally and finalize are given below:
Durga Soft
#202,2nd Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
258 | P a g e
Ans:
final is an access modifier, it can be used with class, it's data members, methods and also with local
variable.
Finally: it block for exception handling, it executes fot any conditions such, normally terminate or
abnormally terminated.
Finalize: it is method from Object. It will be called automatically, when object is cleared by the
Garbage collector.
3. Is it compulsory for a Try Block to be followed by a Catch Block in Java for Exception
handling?
Ans: Try block needs to be followed by either Catch block or Finally block or both. Any exception
thrown from try block needs to be either caught in the catch block or else any specific tasks to be
performed before code abortion are put in the Finally block.
4. Is there any way to skip Finally block of exception even if some exception occurs in the
exception block?
Ans: If an exception is raised in Try block, control passes to catch block if it exists otherwise to
finally block. Finally block is always executed when an exception occurs and the only way to avoid
execution of any statements in Finally block is by aborting the code forcibly by writing following
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
259 | P a g e
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
260 | P a g e
objects.
All the operations that you perform on a data such as searching, sorting, insertion, manipulation,
deletion etc. can be performed by Java Collections.
Java Collection simply means a single unit of objects. Java Collection framework provides many
interfaces (Set, List, Queue, Deque etc.) and classes (ArrayList, Vector, LinkedList, PriorityQueue,
HashSet, LinkedHashSet, TreeSet etc).
Let us see the hierarchy of collection framework.The java.util package contains all the classes and
interfaces for Collection framework.
Meth
ods
of Collection interface
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
261 | P a g e
There are many methods declared in the Collection interface. They are as follows:
Iterator interface
Iterator interface provides the facility of iterating the elements in forward direction only.
Java ArrayList class uses a dynamic array for storing the elements. It extends AbstractList class
and implements List interface.
Java ArrayList allows random access because array works at the index basis.
In Java ArrayList class, manipulation is slow because a lot of shifting needs to be occurred if any
element is removed from the array list.
Durga Soft
#202, 2ndFloor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
262 | P a g e
Java collection framework was non-generic before JDK 1.5. Since 1.5, it is generic.
Java new generic collection allows you to have only one type of object in collection. Now it is type
safe so typecasting is not required at run time.
al.add(employee);
al.add(student);
al.add(customer);
In generic collection, we specify the type in angular braces. Now ArrayList is forced to have only
specified type of objects in it. If you try to add another type of object, it gives compile time error.
package com.nrit.mnrao.test;
import java.util.ArrayList;
import java.util.Iterator;
System.out.println();
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
263 | P a g e
//2nd way
for(int i=0; i<al.size() ; i++)
{
System.out.print(al.get(i)+"\t");
}
System.out.println();
//3rd way
for (Integer i : al) {
System.out.print(i+"\t");
}
System.out.println();
//4th way
Iterator <Integer> iterator = al.iterator();
while(iterator.hasNext())
{
Integer nextInteger = iterator.next();
System.out.print(nextInteger+"\t");
}
package com.nrit.mnrao.test;
import java.util.ArrayList;
import java.util.Iterator;
if(al.isEmpty())
{
System.out.println("empty");
}
else
{
System.out.println("Not empty");
}
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
264 | P a g e
al.add("java");
al.add("hadoop");
System.out.println(al);
al.add(2, "html");
System.out.println(al);
System.out.println(str);
System.out.println(al);
System.out.println(str1);
System.out.println(al);
System.out.println(al.size());
if(al.isEmpty())
{
System.out.println("empty ");
}
else
{
System.out.println(" not empty ");
}
al.clear();
if(al.isEmpty())
{
System.out.println("empty ");
}
else
{
System.out.println(" not empty ");
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
265 | P a g e
Another example
package com.nrit.mnrao.test;
import java.util.ArrayList;
import java.util.Iterator;
al1.add("hive");
al1.add("sqoop");
al1.add("pig");
al1.add("hbase");
al1.add("mapper");
al2.add("java");
al2.add("jsp");
al2.add("servlet");
al2.add("html");
al2.add("spring");
al2.addAll(al1);
System.out.println(al2);
if(al2.containsAll(al1))
{
System.out.println("contains all");
}
else
{
System.out.println("no contains");
}
al2.remove("hive");
if(al2.containsAll(al1))
{
Durga Soft
#202,2nd Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
266 | P a g e
System.out.println("contains all");
}
else
{
System.out.println("not contain");
}
System.out.println(al2);
System.out.println(al3);
}
}
import java.util.ArrayList;
import java.util.Iterator;
public class TestCollection
{
public static void main(String [] args)
{
ArrayList<String> al = new ArrayList<String>();// creating arraylist
al.add("Ravi");// adding object in arraylist
al.add("Vijay");
al.add("Ravi");
al.add("Ajay");
Durga Soft
#202,2nd Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
267 | P a g e
import java.util.ArrayList;
O/p:
Ravi
Vijay
Ravi
Ajay
Durga Soft
#202, 2ndFloor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
268 | P a g e
import java.util.ArrayList;
import java.util.Iterator;
employee.setEmpNum(1001);
employee.setEmpName("nrit1");
employee.setEmpSalary(5000);
employee.setEmpGender('M');
al.add(employee);
employee.setEmpNum(1002);
employee.setEmpName("nrit2");
employee.setEmpSalary(6000);
employee.setEmpGender('F');
al.add(employee);
employee.setEmpNum(1003);
employee.setEmpName("nrit3");
employee.setEmpSalary(7000);
employee.setEmpGender('M');
al.add(employee);
Durga Soft
#202, 2ndFloor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
269 | P a g e
employee.setEmpNum(1004);
employee.setEmpName("nrit4");
employee.setEmpSalary(4000);
employee.setEmpGender('F');
al.add(employee);
while (iterator.hasNext()) {
Employee emp = iterator.next();
Another Way:
package com.nrit.mnrao.test;
import java.util.ArrayList;
import java.util.Iterator;
Durga Soft
#202,2nd Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
270 | P a g e
employee.setEmpNum(Integer.parseInt(fields[0]));
employee.setEmpName(fields[1]);
employee.setEmpSalary(Double.parseDouble(fields[2]));
employee.setEmpGender(fields[3].charAt(0));
al.add(employee);
fields = record2.split(":");
employee.setEmpNum(Integer.parseInt(fields[0]));
employee.setEmpName(fields[1]);
employee.setEmpSalary(Double.parseDouble(fields[2]));
employee.setEmpGender(fields[3].charAt(0));
al.add(employee);
fields = record3.split(":");
employee.setEmpNum(Integer.parseInt(fields[0]));
employee.setEmpName(fields[1]);
employee.setEmpSalary(Double.parseDouble(fields[2]));
employee.setEmpGender(fields[3].charAt(0));
al.add(employee);
fields = record4.split(":");
employee.setEmpNum(Integer.parseInt(fields[0]));
employee.setEmpName(fields[1]);
employee.setEmpSalary(Double.parseDouble(fields[2]));
employee.setEmpGender(fields[3].charAt(0));
al.add(employee);
while (iterator.hasNext()) {
Employee emp = iterator.next();
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
271 | P a g e
}
=======================
Using foreach:
package com.nrit.mnrao.test;
import java.util.ArrayList;
import java.util.Iterator;
employee.setEmpNum(Integer.parseInt(fields[0]));
employee.setEmpName(fields[1]);
employee.setEmpSalary(Double.parseDouble(fields[2]));
employee.setEmpGender(fields[3].charAt(0));
al.add(employee);
fields = record2.split(":");
employee.setEmpNum(Integer.parseInt(fields[0]));
employee.setEmpName(fields[1]);
Durga Soft
#202,2nd Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
272 | P a g e
employee.setEmpSalary(Double.parseDouble(fields[2]));
employee.setEmpGender(fields[3].charAt(0));
al.add(employee);
fields = record3.split(":");
employee.setEmpNum(Integer.parseInt(fields[0]));
employee.setEmpName(fields[1]);
employee.setEmpSalary(Double.parseDouble(fields[2]));
employee.setEmpGender(fields[3].charAt(0));
al.add(employee);
fields = record4.split(":");
employee.setEmpNum(Integer.parseInt(fields[0]));
employee.setEmpName(fields[1]);
employee.setEmpSalary(Double.parseDouble(fields[2]));
employee.setEmpGender(fields[3].charAt(0));
al.add(employee);
}
}
Durga Soft
#202,2nd Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
273 | P a g e
Java LinkedList class uses doubly linked list to store the elements. It extends the AbstractList class
and implements List and Deque interfaces.
import java.util.*;
public class Test
{
public static void main(String [] args)
{
al.add("Ravi");
al.add("Vijay");
al.add("Ravi");
al.add("Ajay");
Iterator<String> itr=al.iterator();
while(itr.hasNext())
{
System.out.println (itr.next());
}
}
}
Output:
Ravi
Vijay
Ravi
Ajay
Difference between ArrayList and LinkedList
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
274 | P a g e
ArrayList and LinkedList both implements List interface and maintains insertion order. Both are non
synchronized classes.
But there are many differences between ArrayList and LinkedList classes that are given below.
ArrayList LinkedList
1) ArrayList internally uses dynamic array to LinkedList internally uses doubly linked list to
store the elements store the elements.
2) Manipulation with ArrayList is slow because Manipulation with LinkedList is faster than
it internally uses array. If any element is ArrayList because it uses doubly linked list so
removed from thekey array, all the bits are no bit shifting is required in memory.
shifted in memory.
3) ArrayList class can act as a list only because LinkedList class can act as a list and queue both
it implements List only. because it implements List and Deque
interfaces.
4) ArrayList is better for storing and accessing LinkedList is better for manipulating data.
data.
Let's see a simple example where we are using ArrayList and LinkedList both.
import java.util.LinkedList;
import java.util.List;
import java.util.ArrayList;
Output:
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
275 | P a g e
arraylist: [Ravi,Vijay,Ravi,Ajay]
linkedlist: [James,Serena,Swati,Junaid]
Vector:
The java.util.Vector class implements a growable array of objects. Similar to an Array, it contains
components that can be accessed using an integer index.
The size of a Vector can grow or shrink as needed to accommodate adding and removing items.
Vector is synchronized.
. Class declaration
Following is the declaration for java.util.Vector class:
Vector()
This constructor is used to create an empty vector so that its internal data array has size 10 and its
standard capacity increment is zero.
This constructor is used to create a vector containing the elements of the specified collection, in the
order they are returned by the collection's iterator.
Vector(int initialCapacity)
This constructor is used to create an empty vector with the specified initial capacity and with its
capacity increment equal to zero.
This constructor is used to create an empty vector with the specified initial capacity and capacity
increment.
boolean add(E e)
This method appends the specified element to the end of this Vector.
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
276 | P a g e
This method inserts the specified element at the specified position in this Vector
This method appends all of the elements in the specified Collection to the end of this Vector.
This method inserts all of the elements in the specified Collection into this Vector at the
specified position.
This method adds the specified component to the end of this vector, increasing its size by one.
int capacity()
void clear()
Clone clone()
boolean contains(Object o)
This method returns true if this vector contains the specified element.
boolean containsAll(Collection<?> c)
This method returns true if this Vector contains all of the elements in the specified Collection.
E elementAt(int index)
This method returns the component at the specified index.
Durga Soft
#202,2nd Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
277 | P a g e
Enumeration<E> elements()
This method returns an enumeration of the components of this vector.
This method increases the capacity of this vector, if necessary, to ensure that it can hold at least
the number of components specified by the minimum capacity argument.
boolean equals(Object o)
This method compares the specified Object with this Vector for equality.
E firstElement()
This method returns the first component (the item at index 0) of this vector.
E get(int index)
This method returns the element at the specified position in this Vector.
int hashCode()
This method returns the hash code value for this Vector.
int indexOf(Object o)
This method returns the index of the first occurrence of the specified element in this vector, or -
1 if this vector does not contain the element.
This method returns the index of the first occurrence of the specified element in this vector,
searching forwards from index, or returns -1 if the element is not found.
This method inserts the specified object as a component in this vector at the specified index.
boolean isEmpty()
E lastElement()
int lastIndexOf(Object o)
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
278 | P a g e
This method returns the index of the last occurrence of the specified element in this vector, or -
1 if this vector does not contain the element.
This method returns the index of the last occurrence of the specified element in this vector,
searching backwards from index, or returns -1 if the element is not found.
E remove(int index)
This method removes the element at the specified position in this Vector.
boolean remove(Object o)
This method removes the first occurrence of the specified element in this Vector If the Vector
does not contain the element, it is unchanged.
boolean removeAll(Collection<?> c)
This method removes from this Vector all of its elements that are contained in the specified
Collection.
void removeAllElements()
This method removes all components from this vector and sets its size to zero.
This method removes the first occurrence of the argument from this vector.
boolean retainAll(Collection<?> c)
This method retains only the elements in this Vector that are contained in the specified
Collection.
This method replaces the element at the specified position in this Vector with the specified
element.
Durga Soft
#202, 2ndFloor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
279 | P a g e
This method sets the component at the specified index of this vector to be the specified object.
int size()
This method returns a view of the portion of this List between fromIndex, inclusive, and
toIndex, exclusive.
object[ ] toArray()
This method returns an array containing all of the elements in this Vector in the correct order.
<T> T[ ] toArray(T[ ] a)
This method returns an array containing all of the elements in this Vector in the correct order;
the runtime type of the returned array is that of the specified array.
String toString()
This method returns a string representation of this Vector, containing the String representation
of each element.
void trimToSize()
This method trims the capacity of this vector to be the vector's current size.
package com.nrit.mnrao.test;
import java.util.Vector;
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
280 | P a g e
System.out.println(vct);
// adding element at specified index
vct.add(2, "Random");
System.out.println(vct);
// getting elements by index
System.out.println("Element at index 3 is: " + vct.get(3));
// getting first element
System.out.println("The first element of this vector is: " + vct.firstElement());
// getting last element
System.out.println("The last element of this vector is: " + vct.lastElement());
// how to check vector is empty or not
System.out.println("Is this vector empty? " + vct.isEmpty());
}
}
Output:
[First, Second, Third]
[First, Second, Random, Third]
Element at index 3 is: Third
The first element of this vector is: First
The last element of this vector is: Third
Is this vector empty? false
import java.util.Iterator;
import java.util.Vector;
Durga Soft
#202, 2ndFloor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
281 | P a g e
Random
package com.nrit.mnrao.test;
import java.util.Enumeration;
import java.util.Vector;
while (enm.hasMoreElements()) {
System.out.println(enm.nextElement());
}
}
import java.util.Vector;
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
282 | P a g e
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
list.add("one");
list.add("two");
vct.addAll(list);
System.out.println("After Copy: " + vct);
}
import java.util.Vector;
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
283 | P a g e
Program: How to find does vector contains all list elements or not?
package com.nrit.mnrao.test;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
public class MyElementCheck {
vct.copyInto(copyArr);
System.out.println("Copied Array content:");
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
284 | P a g e
import java.util.List;
import java.util.Vector;
ArrayList and Vector both implements List interface and maintains insertion order.
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
285 | P a g e
Stack Class
Stack is a subclass of Vector that implements a standard last-in, first-out stack. Stack only defines
the default constructor, which creates an empty stack. Stack includes all the methods defined by
Vector, and adds several of its own.
To put an object on the top of the stack, call push(). To remove and return the top element, call
pop(). An EmptyStackException is thrown if you call pop( ) when the invoking stack is empty. You
can use peek( ) to return, but not remove, the top object.
The empty() method returns true if nothing is on the stack. The search() method determines
whether an object exists on the stack, and returns the number of pops that are required to bring it to
the top of the stack. Here is an example that creates a stack, pushes several Integer objects onto it,
and then pops them off again:
Class declaration
Following is the declaration for java.util.Stack class:
Stack()
boolean empty()
E peek()
This method looks at the object at the top of this stack without removing it from the stack.
E pop()
This method removes the object at the top of this stack and returns that object as the value of
this function. It stack is empty it thorws “EmptyStackException”
E push(E item)
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
286 | P a g e
int search(Object o)
This method returns the 1-based position where an object is on this stack.
package com.nrit.mnrao.test;
import java.util.Stack;
bookRack.push("HADOOP");
bookRack.push("JAVA");
bookRack.push("ORACLE");
bookRack.push("C");
bookRack.push("LINUX");
book = bookRack.pop();
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
287 | P a g e
package com.nrit.mnrao.test;
import java.util.Stack;
bookRack.push("HADOOP");
bookRack.push("JAVA");
bookRack.push("ORACLE");
bookRack.push("C");
bookRack.push("LINUX");
while(! bookRack.empty())
{
String book = bookRack.pop();
System.out.println(book);
}
}
}
uses hashtable to store the elements.It extends AbstractSet class and implements Set interface.
contains unique elements only.
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
288 | P a g e
import java.util.Iterator;
import java.util.HashSet;
TreeSet class:
TreeSet class implements the Set interface that uses a tree for storage. It inherits AbstractSet class
and implements NavigableSet interface. The objects of TreeSet class are stored in ascending order.
import java.util.Iterator;
import java.util.TreeSet;
Durga Soft
#202, 2ndFloor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
289 | P a g e
System.out.println (itr.next());
}
}
}
A map contains values based on the key i.e. key and value pair.
Each pair is known as an entry.
Map contains only unique elements.
public Object put(object key,Object value): is used to insert an entry in this map.
public void putAll(Map map): is used to insert the specified map in this map.
public Object remove(object key): is used to delete an entry for the specified key.
public Object get(Object key): is used to return the value for the specified key.
public boolean containsKey(Object key): is used to search the specified key from this map.
public boolean containsValue(Object value): is used to search the specified value from this
map.
public Set keySet(): returns the Set view containing all the keys.
public Set entrySet(): returns the Set view containing all the keys and values.
A HashMap contains values based on the key. It implements the Map interface and extends
AbstractMap class.
HashSet contains only values whereas HashMap contains entry(key and value).
Durga Soft
#202, 2ndFloor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
290 | P a g e
Non generic Example for HashMap ( any key and any value )
import java.util.HashMap;
import java.util.Stack;
hmap.put(1, "java");
hmap.put("hello", 1);
hmap.put(2, new Employee());
System.out.println(hmap);
}
}
import java.util.HashMap;
import java.util.Stack;
public class Test {
hmap.put(1, "java");
hmap.put(2,"hadoop");
hmap.put(3, "oracle");
hmap.put(4, "unix");
System.out.println(hmap);
}
}
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
291 | P a g e
Another Example
package com.nrit.mnrao.test;
import java.util.HashMap;
public class Test {
package com.nrit.mnrao.test;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
public class Test {
hmap.put(1, "java");
hmap.put(2, "hadoop");
hmap.put(3, "oracle");
hmap.put(4, "unix");
hmap.put(5, "linux");
while(iterator.hasNext())
{
Integer nextKey = iterator.next();
System.out.println(hmap.get(nextKey));
}
}
}
Durga Soft
#202, 2ndFloor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
292 | P a g e
package com.nrit.mnrao.test;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.Set;
public class Test {
hmap.put(1, "java");
hmap.put(2, "hadoop");
hmap.put(3, "oracle");
hmap.put(4, "unix");
hmap.put(5, "linux");
while(iterator.hasNext())
{
Entry<Integer, String> nextEntry = iterator.next();
}
}
}
package com.nrit.mnrao.test;
import java.util.HashMap;
public class Test {
hmap.put(1, "java");
hmap.put(2, "hadoop");
hmap.put(3, "oracle");
hmap.put(4, "unix");
hmap.put(5, "linux");
System.out.println(hmap);
Durga Soft
#202, 2ndFloor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
293 | P a g e
if(hmap.containsKey(4) )
{
String value = hmap.get(4);
if(value.equals("unix"))
{
hmap.replace(4, "unix", "linux");
}
}
System.out.println(hmap);
}
}
package com.nrit.mnrao.test;
import java.util.HashMap;
public class Test {
hmap.put(1, "java");
hmap.put(2, "hadoop");
hmap.put(3, "oracle");
hmap.put(4, "unix");
hmap.put(5, "linux");
System.out.println(hmap);
if(hmap.containsKey(4) )
{
if(hmap.replace(4, "unix", "linux"))
{
System.out.println("successfully replaced");
}
else
{
System.out.println("failed to replace");
}
}
System.out.println(hmap);
}
}
Durga Soft
#202, 2ndFloor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
294 | P a g e
Database properties
import java.util.HashMap;
dataBaseproperties.put("user", "demo");
dataBaseproperties.put("path", "/home/demo");
dataBaseproperties.put("host", "160.10.20.3");
dataBaseproperties.put("dbname", "student");
dataBaseproperties.put("uid", "root");
dataBaseproperties.put("pwd", "admin123");
System.out.println (uidValue);
System.out.println (pwdValue);
System.out.println (pathValue);
System.out.println (userValue);
System.out.println (dataBaseproperties.toString());
}
}
Hashtable class:
Hashtable class implements a Map inetrface, which maps keys to values. It inherits Dictionary class
and implements the Map interface.
A Hashtable is an array of list. Each list is known as a bucket. The position of bucket is identified by
calling the hashcode() method. A Hashtable contains values based on the key.
It is synchronized
import java.util.Hashtable;
Durga Soft
#202, 2ndFloor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
295 | P a g e
import java.util.Iterator;
import java.util.Map;
import java.util.TreeSet;
hm.put(100, "Amit");
hm.put(102, "Ravi");
hm.put(101, "Vijay");
hm.put(103, "Rahul");
Durga Soft
#202, 2ndFloor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
296 | P a g e
Collections class:
collection class is used exclusively with static methods that operate on or return collections. It
inherits Object class.
Java Collection class supports the polymorphic algorithms that operate on collections.
Java Collection class throws a NullPointerException if the collections or class objects provided to
them are null.
Method Description
static <T> boolean addAll(Collection<? super T> c, T... It is used to add all of the specified
elements) elements to the specified collection.
static <T> Queue<T> asLifoQueue(Deque<T> deque) It is used to return a view of a Deque as a
Last-In-First-Out (LIFO) Queue.
static <T> int binarySearch(List<? extends T> list, T key, It is used to search the specified list for the
Comparator<? super T< c) specified object using the binary search
algorithm.
static <E> List<E> checkedList(List<E> list, Class<E> It is used to return a dynamically typesafe
type) view of the specified list.
static <E> Set<E> checkedSet(Set<E> s, Class<E> type) It is used to return a dynamically typesafe
view of the specified set.
static<E> SortedSet<E>checkedSortedSet(SortedSet<E> It is used to return a dynamically typesafe
s, Class<E> type) view of the specified sorted set
static void reverse(List<?> list) It is used to reverse the order of the
elements in the specified list.
static <T> T max(Collection<? extends T> coll, It is used to return the maximum element of
Comparator<? super T> comp) the given collection, according to the order
induced by the specified comparator.
static <T extends Object & Comparable<? super T>>T It is used to return the minimum element of
min(Collection<? extends T> coll) the given collection, according to the
natural ordering of its elements.
static boolean replaceAll(List list, T oldVal, T newVal) It is used to replace all occurrences of one
specified value in a list with another.
Durga Soft
#202, 2ndFloor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
297 | P a g e
Collections Example:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Test
{
public static void main(String a[])
{
List<String> list = new ArrayList<String>();
list.add("C");
list.add("Core Java");
list.add("Advance Java");
Collections.addAll(list, strArr);
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
Durga Soft
#202, 2ndFloor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
298 | P a g e
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
list.add(46);
list.add(67);
list.add(24);
list.add(16);
list.add(8);
list.add(12);
Sorting in Collection:
We can sort the elements of:
String objects
Wrapper class objects
User-defined class objects
Collections class provides static methods for sorting the elements of collection.
Collections class provides methods for sorting the elements of List type elements.
public void sort(List list): is used to sort the elements of List.List elements must be of Comparable
type.
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
299 | P a g e
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
Collections.sort(al);
Iterator itr = al.iterator();
while (itr.hasNext()) {
System.out.println (itr.next());
}
}
}
Example of Sorting the elements of List that contains Wrapper class objects:
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
public class Test
{
public static void main(String [] args)
{
ArrayList al = new ArrayList();
al.add(Integer.valueOf(201));
al.add(Integer.valueOf(101));
al.add(230);// internally will be converted into objects as
// Integer.valueOf(230)
Collections.sort(al);
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
300 | P a g e
The properties object contains key and value pair both as a string. It is the subclass of Hashtable.
It can be used to get property value based on the property key. The Properties class provides methods
to get data from properties file and store data into properties file. Moreover, it can be used to get
properties of system.
Advantage of properties file
Easy Maintenance: If any information is changed from the properties file, you don't need to
recompile the java class. It is mainly used to contain variable information i.e. to be changed.
Method Description
public void load(Reader r) loads data from the Reader object.
public void load(InputStream is) loads data from the InputStream object
public String getProperty(String key) returns value based on the key.
public void setProperty(String key,String sets the property in the properties object.
value)
public void store(Writer w, String comment) writers the properties in the writer object.
public void store(OutputStream os, String writes the properties in the OutputStream
comment) object.
storeToXML(OutputStream os, String writers the properties in the writer object for
comment) generating xml document.
public void storeToXML(Writer w, String writers the properties in the writer object for
comment, String encoding) generating xml document with specified
encoding.
To get information from the properties file, create the properties file first.
db.properties file
===========
user=system
password=oracle
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
301 | P a g e
Test.java
import java.util.*;
import java.io.*;
public class Test
{
public static void main(String[] args)throws Exception
{
FileReader reader=new FileReader("db.properties");
p.load(reader);
System.out.println (p.getProperty("user"));
System.out.println (p.getProperty("password"));
}
}
Now if you change the value of the properties file, you don't need to compile the java class again.
That means no maintenance problem.
Durga Soft
#202, 2ndFloor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
302 | P a g e
Interview Questions
1) What is the difference between ArrayList and Vector?
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
303 | P a g e
The hashCode() method returns the same integer number, if two keys (by calling equals() method)
are same.
But, it is possible that two hash code numbers can have different or same keys.
For example, Employee is a class that has 3 data members: id, name and salary. But, we want to
check the equality of employee object on the basis of salary. Then, we need to override the equals()
method.
Durga Soft
#202, 2ndFloor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
304 | P a g e
20) What is the default size of load factor in hashing based collection?
The default size of load factor is 0.75. The default capacity is computed as initial capacity * load
factor. For example, 16 * 0.75 = 12. So, 12 is the default capacity of Map.
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
305 | P a g e
Java I/O (Input and Output) is used to process the input and produce the output based on the input.
Java uses the concept of stream to make I/O operation fast. The java.io package contains all the
classes required for input and output operations.
Stream:
A stream is a sequence of data. In Java a stream is composed of bytes. It's called a stream because it's
like a stream of water that continues to flow.
In java, 3 streams are created for us automatically. All these streams are attached with console.
3) System.err: standard error stream ( System errors i.e JVM error message )
Let's see the code to print output and error message to the console.
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
306 | P a g e
Byte Streams
A byte stream access the file byte by byte. Java programs use byte streams to perform input and
output of 8-bit bytes. It is suitable for any kind of file, however not quite appropriate for text files.
For example, if the file is using a unicode encoding and a character is represented with two bytes, the
byte stream will treat these separately and you will need to do the conversion yourself. Byte oriented
streams do not use any encoding scheme while Character oriented streams use character encoding
scheme(UNICODE). All byte stream classes are descended from InputStream and OutputStream .
Character Streams
A character stream will read a file character by character. Character Stream is a higher level concept
than Byte Stream . A Character Stream is, effectively, a Byte Stream that has been wrapped with
logic that allows it to output characters from a specific encoding . That means, a character stream
needs to be given the file's encoding in order to work properly. Character stream can support all types
of character sets ASCII, Unicode, UTF-8, UTF-16 etc. All character stream classes are descended
from Reader and Writer .
Durga Soft
#202, 2ndFloor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
307 | P a g e
OutputStream class
OutputStream class is an abstract class.It is the superclass of all classes representing an output stream
of bytes. An output stream accepts output bytes and sends them to some sink.
InputStream class
InputStream class is an abstract class.It is the superclass of all classes representing an input stream of
bytes.
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
308 | P a g e
File Class :
Since java is an independent of plat form we should common code for both OS.
File file = new File(“c:/project/test/file1”);
file.pathSeparator
file.pathSeparatorChar : OS file path separator.
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
309 | P a g e
package com.nrit.mnrao.test;
import java.io.File;
import java.util.Date;
if(file1.exists())
{
System.out.println("exist ");
}
else
{
System.out.println("does not exist ");
}
if(file1.isFile())
{
System.out.println("it is a file");
}
else
{
System.out.println("Not a file");
}
if(file1.isDirectory())
{
System.out.println("it is a directory");
}
else
{
System.out.println("Not a directory");
}
if(file1.canRead())
{
System.out.println("can read ");
}
else
{
System.out.println("can not read");
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
310 | P a g e
}
if(file1.canWrite())
{
System.out.println("can be modified ");
}
else
{
System.out.println("can not be modified");
}
if(file1.canExecute())
{
System.out.println("can be executed ");
}
else
{
System.out.println("can not be executed");
}
System.out.println("parent: "+parent);
System.out.println("name :"+name);
if( file1.renameTo(file2) )
{
System.out.println("renamed");
}
else
{
System.out.println("failed to rename");
}
}
}
Durga Soft
#202, 2ndFloor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
311 | P a g e
Pass file path as command line params and run the abve program
if(filePath.createNewFile())
{
System.out.println("created");
}
else
{
System.out.println("failed");
}
To delete file:
filePath.deleteOnExit();
In Java, FileInputStream and FileOutputStream classes are used for file handling in java.
If you have to write primitive values then use FileOutputStream.Instead, for character-oriented data,
prefer FileWriter.But you can write byte-oriented as well as character-oriented data.
step1:
$gedit Create.java
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
312 | P a g e
(or)
D:\test>notepad Create.java
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
if(args.length!=1)
{
System.out.println("invalid syntax, usage: java Create <file_name>");
System.exit(0);
}
if(filePath.exists())
{
System.out.println(args[0]+" already exist, can not create");
System.exit(0);
}
FileOutputStream fos=null;
try
{
while(ch!=(char)-1)
{
fos.write(ch);
ch = (char )System.in.read();
}
fos.flush();
fos.close();
System.out.println("Successfully created");
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
313 | P a g e
if(fos!=null)
{
fos.close();
}
}
$javac Create.java
Output:
Successfullly created
$gedit Display.java
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
if(args.length!=1)
{
System.out.println("invalid syntax, usage: java Display <file_name>");
System.exit(0);
}
if(!inputFile.exists())
{
System.out.println(args[0]+" file not found ");
System.exit(0);
if(!inputFile.isFile())
{
System.out.println(args[0]+"not a file ");
System.exit(0);
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
314 | P a g e
while(ch!=(char)-1)
{
System.out.print(ch);
ch = (char)fis.read();
}
fis.close();
}
catch (Exception e) {
e.printStackTrace();
}
finally
{
if(fis!=null)
{
fis.close();
}
}
}
}
$javac Display.java
Copying files.
$gedit Copy.java
import java.io.IOException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
if(args.length!=2)
{
System.out.println ("Invalid Syntax usage: java Copy <source_filename>
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
315 | P a g e
<dest_filename> ");
System.exit(0);
}
if(!sourceFile.exists())
{
System.out.println (args[0]+" does not exist can not copy");
System.exit(0);
}
if(destFile.exists())
{
System.out.println (args[1]+" already exist can not copy");
System.exit(0);
}
FileInputStream fis=null;
FileOutputStream fos=null;
try
{
fis = new FileInputStream(args[0]);
fos=new FileOutputStream(args[1]);
while(ch!=(char)-1)
{
fos.write(ch);
ch =(char) fis.read();
}
fis.close();
fos.close();
}
catch(Exception e)
{
Durga Soft
#202, 2ndFloor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
316 | P a g e
e.printStackTrace();
}
finally
{
if(fis!=null)
{
fis.close();
if(fos!=null)
{
fos.close();
}
}
}
$javac Copy.java
Program to read emplyeee records from the "employee.dat" file and has to display 1st filed, 2nd field
and 5th field.
1001:Sri Ram:5000.0:male:dev
1002:Manoj:6000.0:male:admin
1003:Anusha:6500.0:feamle:testing
1004:prasad:5500.0:male:dev
Durga Soft
#202, 2ndFloor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
317 | P a g e
1005:vinay:3500.0:male:finance
1006:mithun:5500.0:male:admin
1007:thirumala:8500.0:female:dev
1050:nrit1:10000.0:male:admin
1051:nrit2:11000.0:female:dev
1011:Sri Ram:5000.0:male:dev
1012:Manoj:6000.0:male:admin
1013:Anusha:6500.0:female:testing
1014:prasad:5500.0:male:dev
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
if(args.length!=1)
{
System.out.println("Invalid Syntax, Uasge: EmpDataFilter
<empdata_file>");
System.exit(0);
}
if(!fileName.equalsIgnoreCase("EMPLOYEE.dat"))
{
System.out.println("invalid file and missing data file");
System.exit(0);
}
try
{
fis = new FileInputStream(file);
dis = new DataInputStream(fis);
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
318 | P a g e
System.out.println(result);
record =dis.readLine();
}
dis.close();
fis.close();
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
if(dis!=null)
{
dis.close();
}
if(fis!=null)
{
fis.close();
}
}
}
}
O/P:
1001:Sri Ram:dev
1002:Manoj:admin
1003:Anusha:testing
1004:prasad:dev
1005:vinay:finance
1006:mithun:admin
1007:thirumala:dev
1050:nrit1:admin
1051:nrit2:dev
1011:Sri Ram:dev
1012:Manoj:admin
Durga Soft
#202, 2ndFloor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
319 | P a g e
1013:Anusha:testing
1014:prasad:dev
1001:Sri Ram:5000.0:male:dev
1002:Manoj:6000.0:male:admin
1003:Anusha:6500.0:feamle:testing
1004:prasad:5500.0:male:dev
1005:vinay:3500.0:male:finance
1006:mithun:5500.0:male:admin
1007:thirumala:8500.0:female:dev
1050:nrit1:10000.0:male:admin
1051:nrit2:11000.0:female:dev
1011:Sri Ram:5000.0:male:dev
1012:Manoj:6000.0:male:admin
1013:Anusha:6500.0:female:testing
1014:prasad:5500.0:male:dev
program:
package com.nrit.mnrao.test;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
if(args.length!=2)
{
System.out.println("Invalid Syntax, Uasge: EmpDataCSVFIle
<empdata_file_path> <empcsv_file_path> ");
System.exit(0);
}
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
320 | P a g e
try
{
fis =new FileInputStream(empDataFilePath);
dis = new DataInputStream(fis);
fos = new FileOutputStream(empDataCsvFilePath);
dos = new DataOutputStream(fos);
dos.writeBytes(result+"\n");
record = dis.readLine();
dis.close();
fis.close();
dos.close();
fos.close();
System.out.println("Successfully converted");
}
catch(Exception e )
{
e.printStackTrace();
}
finally
{
if(dis!=null)
{
dis.close();
}
if(fis!=null)
{
fis.close();
}
if(dos!=null)
{
dos.close();
}
if(fos!=null)
{
fos.close();
}
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
321 | P a g e
1001,Sri Ram,5000.0,male,dev
1002,Manoj,6000.0,male,admin
1003,Anusha,6500.0,feamle,testing
1004,prasad,5500.0,male,dev
1005,vinay,3500.0,male,finance
1006,mithun,5500.0,male,admin
1007,thirumala,8500.0,female,dev
1050,nrit1,10000.0,male,admin
1051,nrit2,11000.0,female,dev
1011,Sri Ram,5000.0,male,dev
1012,Manoj,6000.0,male,admin
1013,Anusha,6500.0,female,testing
1014,prasad,5500.0,male,dev
Program to read records from text file, convert into Employee object and store into ArrayList
and display from ArrayList
package com.nrit.mnrao.test;
Durga Soft
#202, 2ndFloor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
322 | P a g e
package com.nrit.mnrao.test;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
if(args.length!=1)
{
System.out.println("Invalid Syntax, Uasge: EmpDataRead
<empdata_file_path> ");
System.exit(0);
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
323 | P a g e
try
{
fis =new FileInputStream(empDataFilePath);
dis = new DataInputStream(fis);
employee.setEmpNum(Integer.parseInt(fields[0]));
employee.setEmpName(fields[1]);
employee.setEmpSalary(Double.parseDouble(fields[2]));
employee.setEmpGender(fields[3]);
employee.setEmpDept(fields[4]);
empDataList.add(employee);
record = dis.readLine();
dis.close();
fis.close();
while(iterator.hasNext())
{
Employee nextRecord = iterator.next();
System.out.println(
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
324 | P a g e
nextRecord.getEmpNum()+"\t"+
nextRecord.getEmpName()+"\t"+
nextRecord.getEmpSalary()+"\t"+
nextRecord.getEmpGender()+"\t"+
nextRecord.getEmpDept()
);
}
}
catch(Exception e )
{
e.printStackTrace();
}
finally
{
if(dis!=null)
{
dis.close();
}
if(fis!=null)
{
fis.close();
}
}
1001,Sri Ram,5000.0,male,dev
1002,Manoj,6000.0,male,admin
1003,Anusha,6500.0,feamle,testing
1004,prasad,5500.0,male,dev
1005,vinay,3500.0,male,finance
1006,mithun,5500.0,male,admin
1007,thirumala,8500.0,female,dev
1008,nrit1,10000.0,male,admin
1009,nrit2,11000.0,female,dev
1010,Sri Ram,5000.0,male,dev
1011,Manoj,6000.0,male,admin
1012,Anusha,6500.0,female,testing
1013,prasad,5500.0,male,dev
package com.nrit.mnrao.test;
import java.io.DataInputStream;
import java.io.File;
Durga Soft
#202,2nd Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
325 | P a g e
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Iterator;
import java.util.TreeSet;
if (args.length != 1) {
System.out.println("Invalid syntax, Usage: UserValidate
<Src_data_path>");
System.exit(0);
}
if (!file.exists()) {
System.out.println(args[0] + "does not exist");
System.exit(0);
}
try {
deptNames.add(fields[4]);
record = dis.readLine();
dis.close();
fis.close();
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
326 | P a g e
while(iterator.hasNext())
{
String deptName = iterator.next();
System.out.println(deptName);
}
}
catch (Exception e) {
e.printStackTrace();
}
finally
{
if(dis!=null)
{
dis.close();
}
if(fis!=null)
{
fis.close();
}
}
Example that reads the data from two files and writes screen
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.SequenceInputStream;
public class Test
{
public static void main(String[] args) throws IOException
{
File file1 = new File("D:\\testin1.txt");
File file2 = new File("D:\\testin2.txt");
Durga Soft
#202, 2ndFloor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
327 | P a g e
while(ch!=(char)-1)
{
System.out.print(ch);
ch=(char)inst.read();
}
inst.close();
input1.close();
input2.close();
}
}
Example that reads the data from two files and writes into another file
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.SequenceInputStream;
char ch=(char)inst.read();
while(ch!=(char)-1)
{
output.write(ch);
ch=(char)inst.read();
}
inst.close();
input1.close();
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
328 | P a g e
input2.close();
output.close();
}
}
The Java Console class is be used to get input from console. It provides methods to read texts and
passwords.
If you read password using Console class, it will not be displayed to the user.
The java.io.Console class is attached with system console internally. The Console class is introduced
since 1.5.
import java.io.Console;
Durga Soft
#202, 2ndFloor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
329 | P a g e
Password example:
import java.io.Console;
char [] ch = c.readPassword();
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
330 | P a g e
Character Streams
FileReader class:
==================
import java.io.FileReader;
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
331 | P a g e
FileWriter Example:
import java.io.FileWriter;
try
{
FileWriter fw = new FileWriter("D:/testout.txt");
fw.write("Welcome to NR IT Solutions");
fw.close();
}
catch (Exception e)
{
System.out.println (e);
}
System.out.println ("Success...");
}
}
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
}
br.close();
fr.close();
}
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
332 | P a g e
BufferedWriter Example:
import java.io.BufferedWriter;
import java.io.FileWriter;
public class Test
{
public static void main(String[] args) throws Exception
{
FileWriter writer = new FileWriter("D:\\testout.txt");
buffer.write("Welcome to NR IT Solutions\n");
buffer.close();
System.out.println ("Success");
}
}
import java.io.*;
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
333 | P a g e
it provides print() and println () over loaded methods for different data types.
import java.io.FileOutputStream;
import java.io.PrintStream;
public class Test
{
public static void main(String [] args)throws Exception
{
pout.println (2016);
pout.println (2000.50);
pout.println ("Welcome to NR IT Solutions");
pout.close();
fout.close();
System.out.println ("Success?");
}
}
Example of writing the data on a console and in a text file testout.txt using Java PrintWriter
class.
import java.io.File;
import java.io.PrintWriter;
public class Test
{
public static void main(String[] args) throws Exception
{
// Data to write on Console using PrintWriter
PrintWriter writer = new PrintWriter(System.out);
writer.write("Welcome to NR IT Solutions");
writer.flush();
writer.close();
Durga Soft
#202, 2ndFloor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
334 | P a g e
writer1.flush();
writer1.close();
}
}
System.out.printf():
===================
output formatting:
1. Object setProperty(String key, String value) it takes key and value pair
package com.nrit.test;
import java.io.FileReader;
import java.util.Properties;
if (args.length == 0) {
System.out.println("Missing properties file");
System.out.println("Usage: PropTest <prop_file_name>");
System.exit(0);
}
try
{
Properties dbProp = new Properties();
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
335 | P a g e
dbProp.load(propPath);
propPath.close();
}
catch (Exception e) {
System.out.println(e);
}
}
}
import java.io.File;
import java.io.FileInputStream;
import java.util.Iterator;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
try {
fis =new FileInputStream(file);
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
336 | P a g e
while (rowIterator.hasNext())
{
row = (XSSFRow)rowIterator.next();
@SuppressWarnings("rawtypes")
Iterator cellIterator = row.cellIterator();
while (cellIterator.hasNext())
{
cell = (XSSFCell)cellIterator.next();
switch (cell.getCellType())
{
case XSSFCell.CELL_TYPE_BOOLEAN:
currentString.append(cell.getBooleanCellValue() + ",");
break;
case XSSFCell.CELL_TYPE_NUMERIC:
break;
case XSSFCell.CELL_TYPE_STRING:
break;
}
}
currentString.setLength(currentString.length() - 1);
currentString.append("\n");
}
fis.close();
} catch (Exception e) {
}
System.out.println ("String builder : "+currentString.length()+"vaue
"+currentString);
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
337 | P a g e
return finalData;
}
}
===============================================
package com.nrit.mnrao.excel;
import java.io.IOException;
csvFile.generateCSVFile(records, targetFilePath);
In eclipse :
Windows:
D:\\hadoop\\employee.xlsx D:\\hadoop\\emp.csv
Linux:
/home/demo/hadoop employee.xlsx /home/demo/hadoop/ employee.csv
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
338 | P a g e
XML Parser
Using DOM Parser:
Eg:
Sample Data:
Employee.xml:
===================
<employees>
<employee>
<id>111</id>
<firstName>Lokesh</firstName>
<lastName>Gupta</lastName>
<location>India</location>
</employee>
<employee>
<id>222</id>
<firstName>Alex</firstName>
<lastName>Gussin</lastName>
<location>Russia</location>
</employee>
<employee>
<id>333</id>
<firstName>David</firstName>
<lastName>Feezor</lastName>
<location>USA</location>
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
339 | P a g e
</employee>
<employee>
<id>444</id>
<firstName>Russ</firstName>
<lastName>Dawson</lastName>
<location>USA</location>
</employee>
</employees>
111,Lokesh,Gupta,India
222,Alex,Gussin,Russia
333,David,Feezor,USA
444,Russ,Dawson,USA
package com.nrit.mnrao.xml;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
340 | P a g e
// Build Document
try
{
document = builder.parse(dis);
} catch (SAXException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println (nList.getLength());
buffer.append(eElement.getElementsByTagName("id").item(0).getTextContent()
+ ",");
Durga Soft
#202, 2ndFloor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
341 | P a g e
buffer.append(eElement.getElementsByTagName("firstName").item(0).getTextContent()
+ ",");
buffer.append(eElement.getElementsByTagName("lastName").item(0).getTextContent()
+ ",");
buffer.append(eElement.getElementsByTagName("location").item(0).getTextContent());
buffer.append("\n");
}
}
System.out.println (data);
return data;
}
package com.nrit.mnrao.xml;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
try
{
fos = new FileOutputStream(file);
dos = new DataOutputStream(fos);
System.out.println (string);
dos.writeBytes(string+"\n");
}
dos.close();
fos.close();
}
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
342 | P a g e
catch(Exception e)
{
}
finally
{
if(dos!=null)
{
dos.close();
}
if(fos!=null)
{
fos.close();
}
package com.visix.mnrao.xml;
import java.io.IOException;
String keyElement=args[1];
System.out.println (sourceFilePath);
csvFile.generateCSVFile(records, targetFilePath);
System.out.println(“Successfully”);
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
343 | P a g e
}
}
In eclipse :
Windows:
D:\\hadoop\\employee.xml employee D:\\hadoop\\emp.csv
Linux:
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
344 | P a g e
Durga Soft
#202,2nd Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
345 | P a g e
Serialization
Serialization in java is a mechanism of writing the state of an object into a byte stream.
It is mainly used to travel object's state on the network (known as marshaling) or to store object into
the file.
java.io.Serializable interface
Serializable is a marker interface (has no data member and method).
It is used to "mark" java classes so that objects of these classes may get certain capability.
The String class and all the wrapper classes implements java.io.Serializable interface by default.
package com.nrit.test;
import java.io.Serializable;
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
346 | P a g e
ObjectOutputStream class
The ObjectOutputStream class is used to write primitive data types and Java objects to an
OutputStream. Only objects that support the java.io.Serializable interface can be written to streams.
Constructor
1) public final void writeObject(Object obj) throws IOException writes the specified object to
the ObjectOutputStream.
2) public void flush() throws IOException flushes the current output stream.
3) public void close() throws IOException closes the current output stream.
Durga Soft
#202, 2ndFloor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
347 | P a g e
package com.nrit.test;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
public class PersistTest {
try
{
fos = new FileOutputStream("C:/project/test/emp.dat");
oos = new ObjectOutputStream(fos);
System.out.println("Successfully Written");
oos.flush();
oos.close();
fos.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
348 | P a g e
Deserialization
Deserialization is the process of reconstructing the object from the serialized state.It is the reverse
operation of serialization.
ObjectInputStream class
An ObjectInputStream deserializes objects and primitive data written using an ObjectOutputStream.
Constructor
public ObjectInputStream(InputStream in) throws IOException
creates an ObjectInputStream that reads from the specified InputStream.
package com.nrit.test;
import java.io.FileInputStream;
import java.io.ObjectInputStream;
try
{
fis = new FileInputStream("C:/project/test/emp.dat");
ois = new ObjectInputStream(fis);
System.out.println("Fist EMP");
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
349 | P a g e
System.out.println("Second EMP");
obj = ois.readObject();
System.out.println("Third EMP");
obj = ois.readObject();
import java.io.Serializable;
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
350 | P a g e
In case of array or collection, all the objects of array or collection must be serializable. If any object
is not serialiizable, serialization will be failed.
import java.io.Serializable;
import java.io.*;
public class PersistExample
{
out.writeObject(s1);
out.flush();
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
351 | P a g e
out.close();
f.close();
import java.io.*;
public class DePersistTest
{
public static void main(String [] args)throws Exception
{
Student s=(Student)in.readObject();
in.close();
}
}
O/p
111 ravi 0
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
352 | P a g e
Reflection API
Java Reflection is a process of examining or modifying the run time behavior of a class at run time.
The java.lang.Class class provides many methods that can be used to get metadata, examine and
change the run time behavior of a class.
The java.lang and java.lang.reflect packages provide classes for java reflection.
Where it is used
Method Description
1) public String getName()
returns the class name
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
353 | P a g e
There are 3 ways to get the instance of Class class. They are as follows:
package com.nrit.mnrao.test;
public Employee()
{
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
354 | P a g e
return empSalary;
}
public void setEmpSalary(double empSalary) {
this.empSalary = empSalary;
}
public String getEmpDept() {
return empDept;
}
public void setEmpDept(String empDept) {
this.empDept = empDept;
}
@Override
public String toString() {
return "Employee [empNum=" + empNum + ", empName=" + empName + ",
empSalary=" + empSalary + ", empDept="
+ empDept + "]";
}
package com.nrit.mnrao.sample;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
try
{
Class c = Class.forName("com.nrit.mnrao.test.Employee");
System.out.println("Successfully loaded");
System.out.println(conName);
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
355 | P a g e
System.out.println(methodName);
System.out.println("superclass : "+superclass);
}
catch(ClassNotFoundException e)
{
e.printStackTrace();
}
package com.nrit.mnrao.sample;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import com.nrit.mnrao.test.Employee;
try
{
Employee emp = new Employee();
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
356 | P a g e
System.out.println(conName);
System.out.println(methodName);
System.out.println("superclass : "+superclass);
}
catch(Exception e)
{
e.printStackTrace();
}
Durga Soft
#202,2nd Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
357 | P a g e
Multi Threading
Mutli Tasking:
In this for every job separate process creates and loads the job into the process.
If jobs are java program, then JVM loads into every process to execute those programs.
Two JVMs can not share the data. Every one runs in its processes.
For example there are four jobs. Then OS creates four childs and loads four JVMs into that
processes.
2) Priority based scheduling ( four ground job will be given more priority and next is its back
ground
Advantage:
2.No chance of corrupting data as every process has it’s own memory space.
Dis-Advantage :
1.OS has to manage many processes. Hence heavy load on the OS. It is an heavy weight process.
Durga Soft
#202, 2ndFloor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
358 | P a g e
2.Performance is less.
Eg:
UNIX OS
In this concept, only one child process creates for any no of threads and all threads will share same
memory space.
Advantage:
Dis-Advantage
Threading:
Def:
Execution of different parts of same application at the same time is called as multi-threading.
For any no of threads only one child process will be created and that can be shared by all threads of
application.
Adv:
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
359 | P a g e
JVM provides Thread scheduler, which manages different states of the thread.
It is a state of waiting for CPU time. A Thread comes to ready to run state, When start() method is
called on thread.
3) Blocking state:
Thread goes to blocking state when performing I/O operations with external resources, such as
keyboard, database server and other servers.
4) Sleeping state:
It is a state of waiting for shared resources for specific amount of time. A thread goes to sleeping
state when sleep() is called on thread.
5) waiting state
It is state of waiting for the shared resources until getting the resources. Thread goes to waiting state
when wait() method called on thread.
6) suspend state:
Durga Soft
#202,2nd Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
360 | P a g e
If any child thread is going to perform any illegal transactions on the system resources, then main
thread will suspend the child thread. If any thread is in suspend state it should be revoked by some
other thread.
7) Death state:
A thread goes to death state, when terminated normally or abnormally (or) called exit(0) method on
thread.
8) Scheduling : thread scheduler schedules the threads for execution. Thread scheduling can be done
any one of the two ways.
9) yielding :
If any thread enters into ready to run state (new or old thread ) thread scheduler checks priority of
current execution thread with threads which are waiting for CPU time. If waiting thread is having
more priority than the current execution thread, then thread scheduler forcibly brings the current
execution thread into ready to run state.
Creation of a thread :
Runnable interface;
run should be implemented in the child class, which is acting as thread. run() contains thread coding.
Durga Soft
#202, 2ndFloor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
361 | P a g e
Thread class:
1) Thread()
2) Thread(String name)
Methods:
4) public static void sleep(int milliSeconds) to take thread into sleeping state.
Durga Soft
#202, 2ndFloor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
362 | P a g e
}
}
catch(InterruptedException e)
{
System.out.println ("Child Interrupted");
}
t.start();
try
{
for (int i = 0; i < 5; i++)
{
System.out.println ("Parent : " + i);
Thread.sleep(200);
}
}
catch (InterruptedException e)
{
System.out.println ("Parent Interrupted");
}
}
o/p:
parent started
child created
Parent : 0
Child thread started
child : 0
Parent : 1
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
363 | P a g e
child : 1
Parent : 2
child : 2
Parent : 3
child : 3
Parent : 4
child : 4
end of Parent thread
end of child thread
public MyThread()
{
t=new Thread(this,"child");
t.start();
}
new MyThread();
Durga Soft
#202, 2ndFloor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
364 | P a g e
try
{
for (int i = 0; i < 5; i++)
{
System.out.println ("Parent : " + i);
Thread.sleep(200);
}
}
catch (InterruptedException e)
{
System.out.println ("Parent Interrupted");
}
o/p:
parent started
child created
Parent : 0
Child thread started
child : 0
Parent : 1
child : 1
Parent : 2
child : 2
Parent : 3
child : 3
Parent : 4
child : 4
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
365 | P a g e
try
{
for(int i=0;i<5;i++)
{
System.out.println (name+" : "+i);
Thread.sleep(200);
}
}
catch(InterruptedException e)
{
System.out.println ("Child Interrupted name : "+name);
}
}
}
try
{
for (int i = 0; i < threadNames.length; i++)
{
new MyThread(threadNames[i]);
}
Thread.sleep(8000);
}
catch (InterruptedException e)
{
System.out.println ("Parent Interrupted");
}
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
366 | P a g e
Thread priority:
Thread.MAX_PRIORITY =10;
Thread.MIN_PRIORITY = 1;
Methods
String []
threadNames={"One","Two","Three","Four","Five","Six","Seven","eight","nine"};
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
367 | P a g e
currentThread.setPriority(10);
In the above example parent thread dies first and then child . Hence child threads becomes orphaned
threads.
In this scenario we can use join() to wait for the child threads to complete.
Methods:
Thread t;
t.start();
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
368 | P a g e
try
{
t1.t.join();
t2.t.join();
t3.t.join();
catch (InterruptedException e)
{
System.out.println (e.getMessage());
}
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
369 | P a g e
Thread synchronization:
When Multiple threads are trying to access shared resources, there is a chance of crashing threads. To
avoid thread crashing, developer has to write synchronization coding.
the above three methods are from Object class, not from thread class. Hence these can be
called direcly.
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
370 | P a g e
state=false;
notify();
}
state=true;
notify();
Durga Soft
#202, 2ndFloor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
371 | P a g e
}
}
Queue q1;
public Producer(Queue q)
{
q1=q;
t=new Thread(this,"producer");
t.start();
}
int i=0;
while(true)
{
i++;
q1.push(i);
}
}
}
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
372 | P a g e
}
}
}
Interview Questions
1) What is multithreading?
Multithreading is a process of executing multiple threads simultaneously. Its main advantage is:
2) What is thread?
A thread is a lightweight subprocess.It is a separate path of execution.It is called separate path of
execution because each thread runs in a separate stack frame.
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
373 | P a g e
lock.
14)Can Java object be locked down for exclusive use by a given thread?
Yes. You can lock an object by putting it in a "synchronized" block. The locked object is inaccessible
to any thread other than the one that explicitly claimed it.
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
374 | P a g e
17)What is deadlock?
Deadlock is a situation when two threads are waiting on each other to release a resource. Each thread
waiting for a resource which is held by the other waiting thread.
Durga Soft
#202, 2ndFloor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
375 | P a g e
Networking
Java Networking Terminology
The widely used java networking terminologies are given below:
Network :
It is a physical connections between the computer. It can be established by using hub / switch and
Cables.
Networking :
It is a short distance ( in the same Data Centre ) , it can achieved by using HUB or SWITCH.
For long distance ( between two Data Centres located at different location of same building ) . it can
be through the switches or routers.
For very larger distance between different location of citiy. It can be through router.
Eg:
WIFI connection.
Intranet :
Internet :
Hardware components:
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
376 | P a g e
1) Amount of distance
2) Amount of data transferring
3) How frequently data is transferring.
Topology:
Architecture:
In this communication first routing established between source and destination, then communication
starts.
It is a connection oriented (or) TCP based communication
Eg: telephone
Broad casting:
In this communication data will be delivered to all systems in the network and the system will
respond to which data intended.
Eg: radio
1. IP Address
2. Protocol
3. Port Number
4. MAC Address
6. Socket
1) IP Address
IP address is a unique number assigned to a node of a network e.g. 192.168.0.1 . It is composed of
Durga Soft
#202,2nd Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
377 | P a g e
2) Protocol
A protocol is a set of rules basically that is followed for communication. For example:
TCP
FTP
Telnet
SMTP
POP etc.
3) Port Number
The port number is used to uniquely identify different applications. It acts as a communication
endpoint between applications.
The port number is associated with the IP address for communication between two applications.
4) MAC Address
MAC (Media Access Control) Address is a unique identifier of NIC (Network Interface Controller).
A network node can have multiple NIC but each with unique MAC.
But, in connection-less protocol, acknowledgement is not sent by the receiver. So it is not reliable but
fast. The example of connection-less protocol is UDP.
6) Socket
A socket is an endpoint between two way communication.
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
378 | P a g e
Socket class
A socket is simply an endpoint for communications between the machines. The Socket class can be
used to create a socket.
ServerSocket class
The ServerSocket class can be used to create a server socket. This object is used to establish
communication with the clients
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
379 | P a g e
package com.nrit.mnrao.test;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
ServerSocket ss=null;
Socket s =null;
DataInputStream dis=null;
DataOutputStream dos=null;
try
{
ss = new ServerSocket(2341);
s = ss.accept();
while(true)
{
String message = dis.readLine();
System.out.println (message);
dos.writeBytes(message+"\n");
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
380 | P a g e
package com.nrit.mnrao.test;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.Socket;
Socket s=null;
DataInputStream dis=null;
DataInputStream kb=null;
try
{
s = new Socket("localhost",2341);
kb = new DataInputStream(System.in);
while(true)
{
System.out.print("Enter Input : ");
String input = kb.readLine();
dos.writeBytes(input+"\n");
}
catch(Exception e)
{
}
}
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
381 | P a g e
UDP communication:
Java DatagramSocket class represents a connection-less socket for sending and receiving datagram
packets.
A datagram is basically an information but there is no guarantee of its content, arrival or arrival time.
DatagramSocket() throws SocketEeption: it creates a datagram socket and binds it with the
available Port Number on the localhost machine.
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
382 | P a g e
Server:
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Date;
byte [] b = str.getBytes();
,b.length,localHost,2341);
ds.send(dp);
Thread.sleep(5000);
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
Durga Soft
#202, 2ndFloor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
383 | P a g e
Client:
import java.net.DatagramPacket;
import java.net.DatagramSocket;
while(true)
{
byte [] b = new byte[1024];
ds.receive(dp);
b = dp.getData();
Thread.sleep(4000);
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
Durga Soft
#202, 2ndFloor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
384 | P a g e
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Date;
public class UDPMultiServer {
public static void main(String[] args) {
int count=0;
try
{
DatagramSocket ds = new DatagramSocket();
InetAddress localHost = InetAddress.getLocalHost();
while(true)
{
Date currentDate = new Date();
String str = currentDate.toString();
count++;
if(count%2==0)
{
str="Even "+str;
byte [] b = str.getBytes();
DatagramPacket dp = new
DatagramPacket(b,b.length,localHost,2342);
ds.send(dp);
Thread.sleep(5000);
}
else
{
str=" Odd "+str;
byte [] b = str.getBytes();
DatagramPacket dp = new
DatagramPacket(b,b.length,localHost,2341);
ds.send(dp);
Thread.sleep(5000);
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
Durga Soft
#202, 2ndFloor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
385 | P a g e
Client1:
import java.net.DatagramPacket;
import java.net.DatagramSocket;
while(true)
{
byte [] b = new byte[1000];
ds.receive(dp);
b = dp.getData();
Thread.sleep(4000);
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
Durga Soft
#202, 2ndFloor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
386 | P a g e
Client2:
import java.net.DatagramPacket;
import java.net.DatagramSocket;
while(true)
{
byte [] b = new byte[1000];
ds.receive(dp);
b = dp.getData();
Thread.sleep(4000);
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
Java URL
The Java URL class represents an URL. URL is an acronym for Uniform Resource Locator. It
points to a resource on the World Wide Web.
For example:
https://www.google.com:8020/ index.jsp
Durga Soft
#202, 2ndFloor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
387 | P a g e
4. File Name or directory name: In this case, index.jsp is the file name.
import java.net.URL;
}
catch(Exception e)
{
System.out.println (e);
}
}
}
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
388 | P a g e
it returns the instance of InetAdddress containing local host name and address.
import java.net.InetAddress;
Durga Soft
#202, 2ndFloor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
389 | P a g e
The jar (Java Archive) tool of JDK provides the facility to create the executable jar file. An
executable jar file calls the main method of the class if you double click it.
Eg:
D:\sample
Write First.java with following code:
public class First
{
public static void main(String[] args)
{
System.out.println ("Hello World");
}
}
Step2:
For example:
myfile.mf
Main-Class: First
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
390 | P a g e
Now, let's write the code to generated the executable jar using mf file.
You need to write jar then switches then mf_file then jar_file then .classfile as given below:
Durga Soft
#202,2nd Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
391 | P a g e
JVM Architecture
What is the JVM?
A Virtual Machine is a software implementation of a physical machine. Java was developed with
the concept of WORA (Write Once Run Anywhere), which runs on a VM. The compiler compiles
the Java file into a Java .class file, then that .class file is input into the JVM, which Loads and
executes the class file. Below is a diagram of the Architecture of the JVM.
Durga Soft
#202, 2ndFloor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
392 | P a g e
1.1 Loading
Classes will be loaded by this component. Boot Strap class Loader, Extension class Loader, and
Application class Loader are the three class loader which will help in achieving it.
Durga Soft
#202, 2ndFloor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
393 | P a g e
1. Boot Strap ClassLoader – Responsible for loading classes from the bootstrap classpath,
nothing but rt.jar. Highest priority will be given to this loader.
2. Extension ClassLoader – Responsible for loading classes which are inside ext folder
(jre\lib).
3. Application ClassLoader –Responsible for loading Application Level Classpath, path
mentioned Environment Variable etc.
The above Class Loaders will follow Delegation Hierarchy Algorithm while loading the class
files.
1.2 Linking
1. Verify – Bytecode verifier will verify whether the generated bytecode is proper or not if
verification fails we will get the verification error.
2. Prepare – For all static variables memory will be allocated and assigned with default values.
3. Resolve – All symbolic memory references are replaced with the original references from
Method Area.
1.3 Initialization
This is the final phase of Class Loading, here all static variables will be assigned with the original
values, and the static block will be executed.
1. Method Area – All the class level data will be stored here, including static variables. There
is only one method area per JVM, and it is a shared resource.
2. Heap Area – All the Objects and their corresponding instance variables and arrays will be
stored here. There is also one Heap Area per JVM. Since the Method and Heap
areas share memory for multiple threads, the data stored is not thread safe.
3. Stack Area – For every thread, a separate runtime stack will be created. For every method
call, one entry will be made in the stack memory which is called as Stack Frame. All local
variables will be created in the stack memory. The stack area is thread safe since it is not a
shared resource. The Stack Frame is divided into three subentities:
a) Local Variable Array – Related to the method how many local variables are
involved and the corresponding values will be stored here.
b) Operand stack – If any intermediate operation is required to perform, operand stack
acts as runtime workspace to perform the operation.
c) Frame data – All symbols corresponding to the method is stored here. In the case of
any exception, the catch block information will be maintained in the frame data.
4. PC Registers – Each thread will have separate PC Registers, to hold the address of current
executing instruction once the instruction is executed the PC register will be updated with
the next instruction.
5. Native Method stacks – Native Method Stack holds native method information. For every
thread, a separate native method stack will be created.
3. Execution Engine
The bytecode which is assigned to the Runtime Data Area will be executed by the Execution
Engine. The Execution Engine reads the bytecode and executes it piece by piece.
Durga Soft
#202,2nd Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
394 | P a g e
1) Interpreter – The interpreter interprets the bytecode faster, but executes slowly. The
disadvantage of the interpreter is that when one method is called multiple times, every time a
new interpretation is required.
2) JIT Compiler – The JIT Compiler neutralizes the disadvantage of the interpreter. The
Execution Engine will be using the help of the interpreter in converting byte code, but when
it finds repeated code it uses the JIT compiler, which compiles the entire bytecode and
changes it to native code. This native code will be used directly for repeated method calls,
which improve the performance of the system.
3) Garbage Collector: Collects and removes unreferenced objects. Garbage Collection can be
triggered by calling "System.gc()", but the execution is not guaranteed. Garbage collection of
the JVM collects the objects that are created.
Java Native Interface (JNI): JNI will be interacting with the Native Method Libraries and
provides the Native Libraries required for the Execution Engine.
Native Method Libraries:It is a collection of the Native Libraries which is required for the
Execution Engine.
Durga Soft
#202, 2ndFloor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
395 | P a g e
Interview Questions
Ans: An array groups data of same primitive type and is static in nature while vectors are dynamic in
nature and can hold data of different data types.
2. What is multi-threading?
Ans: Multi threading is a programming concept to run multiple tasks in a concurrent manner within a
single program. Threads share same process stack and running in parallel. It helps in performance
improvement of any program.
Ans: In java, when an object is not referenced any more, garbage collection takes place and the
object is destroyed automatically. For automatic garbage collection java calls either System.gc()
method or Runtime.gc() method.
Ans: We can use the concept of cloning to create copy of an object. Using clone, we create copies
with the actual state of an object.
Clone() is a method of Cloneable interface and hence, Cloneable interface needs to be implemented
for making object copies.
Ans: If we want certain variables of a class not to be serialized, we can use the keyword transient
while declaring them. For example, the variable trans_var below is a transient variable and can’t be
serialized:
Ans: Checked exceptions can be caught at the time of program compilation. Checked exceptions
must be handled by using try catch block in the code in order to successfully compile the code.
Java 7 one of the improvement was multi-catch block where we can catch multiple exceptions in a
single catch block. This makes are code shorter and cleaner when every catch block has similar code.
If a catch block handles multiple exception, you can separate them using a pipe (|) and in this case
exception parameter (ex) is final, so you can’t change it.
Durga Soft
#202, 2ndFloor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
396 | P a g e
Java Classloader is the program that loads byte code program into memory when we want to access
any class. We can create our own classloader by extending ClassLoader class and overriding
loadClass(String name) method.
Yes, we can have try-finally statement and hence avoiding catch block.
Garbage Collection is the process of looking at heap memory, identifying which objects are in use
and which are not, and deleting the unused objects. In Java, process of deallocating memory is
handled automatically by the garbage collector.
We can run the garbage collector with code Runtime.getRuntime().gc() or use utility method
System.gc().
We can convert a Java object to an Stream that is called Serialization. Once an object is converted to
Stream, it can be saved to file or send over the network or used in socket connections.
The object should implement Serializable interface and we can use java.io.ObjectOutputStream to
write object to file or to any OutputStream object.
We can run a jar file using java command but it requires Main-Class entry in jar manifest file. Main-
Class is the entry point of the jar and used by java command to execute the class.
Durga Soft
#202, 2ndFloor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
397 | P a g e
Exception :- It is a runtime one, when exception raises application terminates abnormally. It can be
handled by writing exception handling code.
Bug :- It is an unexpected value at runtime. Even bug raises application never terminates
abnormally. It can can be fixed.
Defect :- It can't be fixed. Some features may not be provided by the application software.
ArrayList can grow dynamically and provides more powerful insertion and search mechanisms than
arrays.
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
398 | P a g e
Overriding concept comes in picture with inheritance when we have two methods with same
signature, one in parent class and another in child class. We can use @Override annotation in the
child class overridden method to make sure if parent class method is changed, so as child class.
java.lang package is imported by default and we don’t need to import any class from this package
explicitly.
We can use final keyword with methods to make sure child classes can’t override it.
final keyword can be used with variables to make sure that it can be assigned only once. However
the state of the variable can be changed, for example we can assign a final variable to an object only
once but the object variables can change later on.
static keyword can be used with methods also. A static method can access only static variables of
class and invoke only static methods of the class.
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
399 | P a g e
finalize() is a special method in Object class that we can override in our classes. This method get’s
called by garbage collector when the object is getting garbage collected. This method is usually
overridden to release system resources when object is garbage collected.
From Java 7, we can create resources inside try block and use it. Java takes care of closing it as soon
as try-catch block gets finished.
If a catch block handles multiple exception, you can separate them using a pipe (|) and in this case
exception parameter (ex) is final, so you can’t change it.
abstract keyword is used to create a abstract class. Abstract classes can’t be instantiated and mostly
used to provide base for sub-classes to extend and implement the abstract methods and override or
use the implemented methods in abstract class.
A class can extend only one abstract class but it can implement multiple interfaces.
Durga Soft
#202,2nd Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
400 | P a g e
We can run abstract class if it has main() method whereas we can’t run an interface.
enum is the keyword to create an enum type and similar to class. Enum constants are implicitly static
and final.
Even though we don’t use Reflection API in normal programming, it’s very important to have. We
can’t have any frameworks such as Spring, Hibernate or servers such as Tomcat, JBoss without
Reflection API. They invoke the appropriate methods and instantiate classes through reflection API
and use it a lot for other processing.
Java composition is achieved by using instance variables that refers to other objects. Benefit of using
composition is that we can control the visibility of other object to client classes and reuse only what
we need.
Durga Soft
#202, 2ndFloor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
401 | P a g e
Any change in the superclass might affect subclass even though we might not be using the
superclass methods. For example, if we have a method test() in subclass and suddenly
somebody introduces a method test() in superclass, we will get compilation errors in subclass.
Composition will never face this issue because we are using only what methods we need.
Inheritance exposes all the super class methods and variables to client and if we have no
control in designing superclass, it can lead to security holes. Composition allows us to
provide restricted access to the methods and hence more secure.
We can get runtime binding in composition where inheritance binds the classes at compile
time. So composition provides flexibility in invocation of methods.
However, if you want to sort based on different criteria, such as sorting an Employees collection
based on salary or age, then we can create Comparator instances and pass it as sorting methodology.
We can have local inner class or anonymous inner class inside a class
Since an anonymous class has no name, it is not possible to define a constructor for an anonymous
class. Anonymous inner classes are accessible only at the point where it is defined.
1. Bootstrap Class Loader – It loads JDK internal classes, typically loads rt.jar and other core
classes.
Durga Soft
#202,2nd Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
402 | P a g e
2. Extensions Class Loader – It loads classes from the JDK extensions directory, usually
$JAVA_HOME/lib/ext directory.
3. System Class Loader – It loads classes from the current classpath that can be set while
invoking a program using -cp or -classpath command line options.
We can use super keyword to invoke super class constructor in child class constructor but in this case
it should be the first statement in the constructor method.
public SuperClass(){
}
@Override
public void test(){
System.out.println ("child class test method");
}
}
The continue statement skips the current iteration of a for, while or do-while loop. We can use
Durga Soft
#202, 2ndFloor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
403 | P a g e
continue statement with label to skip the current iteration of outermost loop.
//constructor
public Point(int x, int y) {
this.x = x;
this.y = y;
}
We can also use this keyword to invoke other constructors from a constructor.
public Rectangle() {
this(0, 0, 0, 0);
}
public Rectangle(int width, int height) {
this(0, 0, width, height);
}
public Rectangle(int x, int y, int width, int height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
We can run the garbage collector with code Runtime.getRuntime().gc() or use utility method
System.gc().
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
404 | P a g e
The object should implement Serializable interface and we can use java.io.ObjectOutputStream to
write object to file or to any OutputStream object.
The process of converting stream data created through serialization to Object is called
deserialization.
Answer: The code won’t compile because we can’t have an Object class method with static
keyword. Note that Object class has toString() method. You will get compile time error as “This
static method cannot hide the instance method from Object”. The reason is that static method belongs
to class and since every class base is Object, we can’t have same method in instance as well as in
class. You won’t get this error if you change the method name from toString() to something else that
is not present in super class Object.
Answer: Well this is a strange situation. We all have seen NullPointerException when we invoke a
method on object that is NULL. But here this program will work and prints “Test foo called”.
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
405 | P a g e
The reason for this is the java compiler code optimization. When the java code is compiled to
produced byte code, it figures out that foo() is a static method and should be called using class. So it
changes the method call obj. display () to Test. display () and hence no NullPointerException.
Interface
1)An abstract class can have method body (non-abstract
Interface have only abstract methods.
methods).
An interface cannot have instance
2)An abstract class can have instance variables.
variables.
3)An abstract class can have constructor. Interface cannot have constructor.
4)An abstract class can have static methods. Interface cannot have static methods.
5)You can extends one abstract class. You can implement multiple interfaces.
59) Can I import same package/class twice? Will the JVM load the package twice at runtime?
One can import the same package or same class multiple times. Neither compiler nor JVM complains
about it.But the JVM will internally load the class only once no matter how many times you import
the same class.
By static import, we can access the static members of a class directly, there is no to qualify it with the
class name.
1)Checked Exception
The classes that extend Throwable class except RuntimeException and Error are known as checked
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
406 | P a g e
2)Unchecked Exception
The classes that extend RuntimeException are known as unchecked exceptions e.g.
ArithmeticException,NullPointerException etc. Unchecked exceptions are not checked at compile-
time.
Throwable.
Ans: In java, to convert an object into byte stream by serialization, an interface with the name
Serializable is implemented by the class. All objects of a class implementing serializable interface
get serialized and their state is saved in byte stream.
Ans: Serialization is used when data needs to be transmitted over the network. Using serialization,
object’s state is saved and converted into byte stream .The byte stream is transferred over the
network and the object is re-created at destination.
66) Is it necessary that each try block must be followed by a catch block?
It is not necessary that each try block must be followed by a catch block. It should be followed by
either a catch block OR a finally block. And whatever exceptions are likely to be thrown should be
declared in the throws clause of the method.
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
407 | P a g e
5)You cannot throw multiple You can declare multiple exception e.g. public void
exception method()throws IOException,SQLException.
72) Can subclass overriding method declare an exception if parent class method doesn't throw
an exception ?
Yes but only unchecked exception not checked.
Durga Soft
#202,2nd Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
408 | P a g e
82) Is there any difference between nested classes and inner classes?
Yes, inner classes are non-static nested classes i.e. inner classes are the part of nested classes.
83) Can we access the non-final local variable, inside the local inner class?
No, local variable must be constant if you want to access it in local inner class.
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
409 | P a g e
95)What is the difference between the Reader/Writer class hierarchy and the
IputStream/OutputStream class hierarchy?
The Reader/Writer class hierarchy is character-oriented, and the InputStream/OutputStream class
hierarchy is byte-oriented.
100)What is Externalizable?
Externalizable interface is used to write the state of an object into a byte stream in compressed
format.It is not a marker interface.
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
410 | P a g e
Debugger
Test Tools etc.
104) Can you access the private method from outside the class?
Yes, by changing the runtime behaviour of a class if the class is not secured.
161)What is Locale?
A Locale object represents a specific geographical, political, or cultural region.
Durga Soft
#202, 2ndFloor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
411 | P a g e
1. Collections framework.
2. Java String memory map for constants.
3. Just In Time (JIT) compiler.
4. Jar Signer for signing Java ARchive (JAR) files.
5. Policy Tool for granting access to system resources.
6. Java Foundation Classes (JFC) which consists of Swing 1.0, Drag and Drop, and Java
2D class libraries.
7. Java Plug-in
8. Scrollable result sets, BLOB, CLOB, batch update, user-defined types in JDBC.
9. Audio support in Applets.
Durga Soft
#202, 2ndFloor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
412 | P a g e
9. IPv6 Support
10. Regular Expressions
11. Image I/O API
Released on 30 September 2004 J2SE 1.5 version.
New features in J2SE 1.5
1. Generics
2. Enhanced for Loop
3. Autoboxing/Unboxing
4. Enum
5. Varargs
6. Static Import
7. Metadata (Annotations)
8. Instrumentation
Durga Soft
#202, 2ndFloor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
413 | P a g e
8) Reactive Streams
G:\>jshell
| Welcome to JShell -- Version 9-ea
| For an introduction type: /help intro
jshell> int a = 10
a ==> 10
Durga Soft
#202, 2ndFloor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
414 | P a g e
In Java SE 8 and earlier versions, We can use Collections class utility methods like
unmodifiableXXX to create Immutable Collection objects. For instance, if we want to create an
Immutable List, then we can use Collections.unmodifiableList method.
However these Collections.unmodifiableXXX methods are very tedious and verbose approach. To
overcome those shortcomings, Oracle corp has added couple of utility methods to List, Set and Map
interfaces.
List and Set interfaces have “of()” methods to create an empty or no-empty Immutable List or Set
objects as shown below:
Map has two set of methods: of() methods and ofEntries() methods to create an Immutable Map
object and an Immutable Map.Entry object respectively.
To avoid redundant code and more re-usability, Oracle Corp is going to introduce private methods in
Java SE 9 Interfaces. From Java SE 9 on-wards, we can write private and private static methods too
in an interface using ‘private’ keyword.
Durga Soft
#202, 2ndFloor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
415 | P a g e
These private methods are like other class private methods only, there is no difference between them.
}
4.Java 9 Module System
One of the big changes or java 9 feature is the Module System. Oracle Corp is going to introduce the
following features as part of Jigsaw Project.
Modular JDK
Modular Java Source Code
Modular Run-time Images
Encapsulate Java Internal APIs
Java Platform Module System
Before Java SE 9 versions, we are using Monolithic Jars to develop Java-Based applications. This
architecture has lot of limitations and drawbacks. To avoid all these shortcomings, Java SE 9 is
coming with Module System.
JDK 9 is coming with 92 modules (may change in final release). We can use JDK Modules and also
we can create our own modules as shown below:
Here We are using ‘module’ to create a simple module. Each module has a name, related code and
other resources.
java.lang.ProcessHandle
java.lang.ProcessHandle.Info
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
416 | P a g e
Java SE 9 is going to provide some improvements to this statement to avoid some more verbosity
and improve some Readability.
Java SE 7 example
Java 9 example
Here delayedExecutor() is static utility method used to return a new Executor that submits a task to
the default executor after the given delay.
8.Reactive Streams
Now-a-days, Reactive Programming has become very popular in developing applications to get some
beautiful benefits. Scala, Play, Akka etc. Frameworks has already integrated Reactive Streams and
getting many benefits. Oracle Corps is also introducing new Reactive Streams API in Java SE 9.
Java SE 9 has introduced the following API to develop Reactive Streams in Java-based applications.
java.util.concurrent.Flow
java.util.concurrent.Flow.Publisher
Durga Soft
#202,2nd Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
417 | P a g e
java.util.concurrent.Flow.Subscriber
java.util.concurrent.Flow.Processor
Here we are using just “List” without specifying the type parameter.
If a value present in the given Optional object, this stream() method returns a sequential Stream with
that value. Otherwise, it returns an Empty Stream.
They have added “stream()” method to work on Optional objects lazily as shown below:
Here Optional.stream() method is used convert a Stream of Optional of Employee object into a
Stream of Employee so that we can work on this result lazily in the result code.
If you are familiar with Scala Language or any Functions programming language, you will definitely
know about these methods. These are very useful methods in writing some functional style code. Let
us discuss about takeWhile utility method here.
This takeWhile() takes a predicate as an argument and returns a Stream of subset of the given Stream
values until that Predicate returns false for first time. If first value does NOT satisfy that Predicate, it
just returns an empty Stream.
3
4
In Java SE 9, Oracle Corp has enhanced @Deprecated annotation to provide more information about
deprecated API and also provide a Tool to analyse an application’s static usage of deprecated APIs.
They have add two methods to this Deprecated interface: forRemoval and since to serve this
information.
13.HTTP 2 Client
In Java SE 9, Oracle Corp is going to release New HTTP 2 Client API to support HTTP/2 protocol
and WebSocket features. As existing or Legacy HTTP Client API has numerous issues (like supports
HTTP/1.1 protocol and does not support HTTP/2 protocol and WebSocket, works only in Blocking
mode and lot of performance issues.), they are replacing this HttpURLConnection API with new
HTTP client.
They are going to introduce new HTTP 2 Client API under “java.net.http” package. It supports both
HTTP/1.1 and HTTP/2 protocols. It supports both Synchronous (Blocking Mode) and Asynchronous
Modes. It supports Asynchronous Mode using WebSocket API.
MultiResolutionImage encapsulates a set of images with different Height and Widths (that is
different resolutions) and allows us to query them with our requirements.
Durga Soft
#202, 2ndFloor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
419 | P a g e
As of now, I did not get enough information about these features. That’s why I am going list them
here for brief understanding. I will pickup these Features one by one and add to above section with a
brief discussion and example. And final write a separate tutorial later.
HTML5 Javadoc
Java inner class is defined inside the body of another class. Java inner class can be declared private,
public, protected, or with default access whereas an outer class can have only public or default
access.
If the nested class is static, then it’s called static nested class. Static nested classes can access only
static members of the outer class. Static nested class is same as any other top-level class and is nested
for only packaging convenience.
OuterClass.StaticNestedClass nestedObject =
new OuterClass.StaticNestedClass();
Any non-static nested class is known as inner class in java. Java inner class is associated with the
object of the class and they can access all the variables and methods of the outer class.
Since inner classes are associated with instance, we can’t have any static variables in them.
Object of java inner class are part of the outer class object and to create an instance of inner class, we
first need to create instance of outer class.
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
420 | P a g e
Since local inner class is not associated with Object, we can’t use private, public or protected access
modifiers with it. The only allowed modifiers are abstract or final.
A local inner class can access all the members of the enclosing class and local final variables in the
scope it’s defined.
A local inner class without name is known as anonymous inner class. An anonymous class is defined
and instantiated in a single statement.
Anonymous inner class always extend a class or implement an interface. Since an anonymous class
has no name, it is not possible to define a constructor for an anonymous class.
Anonymous inner classes are accessible only at the point where it is defined.
It’s a bit hard to define how to create anonymous inner class, we will see it’s real time usage in test
program below.
Here is a java class showing how to define java inner class, static nested class, local inner class and
anonymous inner class.
import java.io.File;
import java.io.FilenameFilter;
Durga Soft
#202, 2ndFloor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
421 | P a g e
public int l;
//OuterClass constructor
public OuterClass(int i, int j, int k, int l) {
this.i = i;
this.j = j;
this.k = k;
this.l = l;
}
//inner class, non static and can access all the variables/methods of outer class
class InnerClass {
private int w;
protected int x;
int y;
public int z;
@Override
public String toString() {
return "w=" + w + ":x=" + x + ":y=" + y + ":z=" + z;
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
422 | P a g e
@Override
public boolean accept(File dir, String name) {
return name.endsWith(ext);
}
});
return filesList;
}
}
Here is the test program showing how to instantiate and use inner class in java.
import java.util.Arrays;
//nested classes can be used in import for easy instantiation
import com.journaldev.nested.OuterClass.InnerClass;
Durga Soft
#202, 2ndFloor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
423 | P a g e
import com.journaldev.nested.OuterClass.StaticNestedClass;
System.out.println(staticNestedClass.getName());
staticNestedClass.d=10;
System.out.println(staticNestedClass.d);
System.out.println(staticNestedClass1.d);
System.out.println(Arrays.toString(outer.getFilesInDir("bin/com/journaldev/nested", ".class")));
}
OuterClass
10
0
OuterClass
w=0:x=0:y=0:z=0
w=1:x=2:y=3:z=4
Outer: OuterClass
Outer: 1
Outer: 2
Outer: 3
Outer: 4
[NestedClassTest.java, OuterClass.java]
[NestedClassTest.class, OuterClass$1.class, OuterClass$1Logger.class, OuterClass$InnerClass.class,
OuterClass$StaticNestedClass.class, OuterClass.class]
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
424 | P a g e
Notice that when OuterClass is compiled, separate class files are created for inner class, local inner
class and static nested class.
1. If a class is useful to only one class, it makes sense to keep it nested and together. It helps in
packaging of the classes.
2. Java inner classes implements encapsulation. Note that inner classes can access outer class
private members and at the same time we can hide inner class from outer world.
3. Keeping the small class within top-level classes places the code closer to where it is used and
makes code more readable and maintainable.
Java varargs
varargs in java enables a method to accept variable number of arguments. We use three dots (…) also
known as ellipsis in the method signature to make it accept variable arguments. For example;
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
425 | P a g e
return sum;
}
If you will look at both sum and sumArray methods, you will see that the implementation body is
exactly same. So we should use varargs when API offers them, for example
java.io.PrintStream.printf() method but we should not take it as a replacement for array.
In above example, you will notice that compiler will not complain when we overload methods with
varargs. But when we try to use it, compiler get’s confused which method to use when mapping the
second argument.
If there is only one argument, compiler is smart to use first method because it can work with
minimum one argument but second method needs at least two arguments. Below image from Eclipse
shows the error message as The method sum(int, int[]) is ambiguous for the type VarargsExample.
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
426 | P a g e
Interview Questions
1) A result of expression involving byte, int, and literal numbers is promoted to which of
these?
A. int
B. long
C. byte
D. float
Answer: Option A
Explanation:
An expression involving bytes, ints, shorts, literal numbers, the result of the expression is promoted
to next data type after calculation is done.
A. -128 to 127
B. 0 to 256
C. 0 to 32767
D. 0 to 65535
Answer: Option D
Explanation:
In java Char is a Unicode char, which occupies 16-bit in memory, it supports ranging from 0 to
65535.
Answer: Option A
Explanation:
Boolean variable can contain only one of two possible values, true and false.
A. boolean b1 = 1;
B. boolean b2 = ‘false’;
C. boolean b3 = false;
D. boolean b4 = ‘true’
Durga Soft
#202,2nd Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
427 | P a g e
Answer: Option C
Explanation:
class Test {
public static void main(String args[])
{
boolean var1 = true;
boolean var2 = false;
if (var1)
System.out.println(var1);
else
System.out.println(var2);
}
}
A. 0
B. 1
C. true
D. false
Answer: Option C
Explanation:
true
A. Integers
B. Floating – point numbers
C. Both Integers and floating – point numbers.
D. None of the mentioned
Answer: Option C
Explanation:
Modulus operator can be applied to both integers and floating point numbers.
7) With x = 0, which of the following are valid Java code for changing the value of x to 1?
1. x++;
2. x = x + 1;
3. x += 1;
Durga Soft
#202,2nd Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
428 | P a g e
4. x =+ 1;
A. 1, 2 & 3
B. 1 & 4
C. 1, 2, 3 & 4
D. 3 & 2
Answer: Option A
Explanation:
A. 25
B. 24
C. 32
D. 33
Answer: Option C
Explanation:
A.
11 11
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
429 | P a g e
B.
10 10
C.
11 10
D.
10 11
Answer: Option C
Explanation:
11) Which operator is used to invert all the digits in binary representation of a number?
A. ~
B. >>>
C. ^
D. !
Answer: Option A
Explanation:
Unary not operator, ~, inverts all of the bits of its operand in binary representation.
A. Integer
B. Boolean
C. Characters
D. Double
Answer: Option B
Explanation:
Boolean
1. &&
Durga Soft
#202, 2ndFloor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
430 | P a g e
2. ==
3. ?:
4. +=
A. 3 & 2
B. 1 & 4
C. 1, 2 & 4
D. 1, 2 & 3
Answer: Option D
Explanation:
Operator &&, is equal to( ==) , ternary if-then-else, ?:, are boolean logical operators. += is
an arithmetic operator it can operate only on numeric values.
for( i=0;i++<=10;);
System.out.println(i);
}
A.10
B.11
C.12
D.13
Answer: Option C
C. int arr[];
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
431 | P a g e
Answer: Option D
Explanation:
A) 00 0 0 0
B) 5 ( length of array )
C) 5 garbage values
D) Address of array
Answer : Option D
1) run
2) import
3) default
4) implements
A) 2 and 3
B) 2 and 4
C) 2 , 3 and 4
D) 1 and 2
Answer : Option B
18) Which class or interface defines the wait(), notify(),and notifyAll() methods?
A) Object
B) Runnable
C)Class
D) Thread
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
432 | P a g e
Answer : Option A
19) Which of the following statements is preferred to create a string "Welcome to Java
Programming"?
Options
A) String str = “Welcome to Java Programming”;
B) String str = new String( “Welcome to Java Programming” );
C) String str;
str = “Welcome to Java Programming”;
D) String str;
str = new String (“Welcome to Java Programming” );
Answer : A
Explanation: value of string is known. Compile time is the best.
A) super() constructor is invoked within a method of a class while this() constructor is used
within the constructor of the sub class
B) this() constructor is invoked outside a method of a class while super() constructor is used
within the constructor of the sub class
C) this() constructor is invoked within a method of a class while super() constructor is used
within the constructor of the sub class
D) this() constructor is invoked within a method of a class while super() constructor is used
outside the constructor of the sub class
Answer : Option C
Answer : Option C
Durga Soft
#202, 2ndFloor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
433 | P a g e
Answer : Option A
A) Set
B) LinkedList
C) Vector
D) ArrayList
Answer : Option C
Answer : Option D
Answer : Option C
26) All the wrapper classes (Integer, Boolean, Float, Short, Long, Double and Character) in
java
A) are private
B) are serializable
C) are immutable
D) are final
Answer : Option : D
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
434 | P a g e
29) When a thread terminates its processing, into what state that thread enters?
A) Running state
B)Waiting state
C)Dead state
C) Beginning state
ANSWER : Option C
A) 17, byte
B) 25, byte
C) 17, int
D) 25, int
ANSWER : Option C
ANSWER : Option D
System.out.println(salaries[3]);
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
435 | P a g e
}
A) 10000
B) 20000
C) 30000
D) 40000
Answer : Option A
Answer : Option C
35) After the following code fragment, what is the value in fname?
String str;
int fname;
str = "Foolish boy.";
fname = str.indexOf("fool");
A) 0
B) 1
C) -1
D) 2
Answer : Option C
36) Consider the following code snippet. What will be assigned to the variable fourthChar, if the
code is executed?
Durga Soft
#202,2nd Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
436 | P a g e
B) ‘v’
C) throws StringIndexOutofBoundsException
D) null characater
ANSWER : Option C
ANSWER : Option A
ANSWER : Option B
39) Which of the following is used to obtain length of String object?
A.length
B. size()
C. capacity()
D. length()
Answer : Option D
s1.concat("two");
System.out.println(s1);
A) onetwo
B) one
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
437 | P a g e
C) twoone
D) two
Answer : Option B
41) What is the final vale of s1
String s1 = "hyderabad";
String s2 = s1.replace("bad1","abc");
System.out.println(s2);
A) hyderaabc
B) hyderaabc1
C) hyderabad1
D) hyderabad
Answer : Option D
42) In the following what are the final values of s1 and s2
StringBuffer s1=new StringBuffer("one");
StringBuffer s2 = s1.append("two");
Answer : Option B
43) Which of the following are incorrect form of StringBuffer class constructor?
A. StringBuffer()
B. StringBuffer(int size)
C. StringBuffer(String str)
D. StringBuffer(int size , String str)
Answer: Option D
44) . Which of these process occur automatically by java run time system?
A. Serialization
B. Garbage collection
C. File Filtering
D. All of the mentioned
Answer: Option A
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
438 | P a g e
Explanation:
Serialization and deserialization occur automatically by java run time system, Garbage collection
also occur automatically but is done by CPU or the operating system not by the java run time
system.
45) Which of these is a method of ObjectOutput interface used to finalize the output state so
that any buffers are cleared?
A. clear()
B. flush()
C. fflush()
D. close()
Answer: Option B
Explanation:
flush()
46) Which of these is method of ObjectOutput interface used to write the object to input or
output stream as required?
A. write()
B. Write()
C. StreamWrite()
D. writeObject()
Answer: Option D
Explanation:
writeObject() is used to write an object into invoking stream, it can be input stream or output
stream.
47) Which of these is a process of extracting/removing the state of an object from a stream?
A. Serialization
B. Externalization
C. File Filtering
Durga Soft
#202, 2nd
Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
439 | P a g e
D. Deserialization
Answer: Option D
Explanation:
Deserialization is a process by which the data written in the stream can be extracted out from the
stream.
48) Which of these is a method of ObjectInput interface used to deserialize an object from a
stream?
A. int read()
B. void close()
C. Object readObject()
D. Object WriteObject()
Answer: Option C
Explanation:
Object readObject()
A. Run Time
B. Compilation Time
Answer: Option A
Explanation:
A. try
B. final
C. throws
Durga Soft
#202, 2ndFloor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
440 | P a g e
D. catch
Answer: Option B
Durga Soft
#202,2nd Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com