0% found this document useful (0 votes)
85 views

Java Notes

The document discusses the history and development of Java programming language. It provides details about Java's object-oriented features and how it differs from C and C++. The document also explains applets and various applications of object-oriented programming.

Uploaded by

AABHI
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
85 views

Java Notes

The document discusses the history and development of Java programming language. It provides details about Java's object-oriented features and how it differs from C and C++. The document also explains applets and various applications of object-oriented programming.

Uploaded by

AABHI
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 70

JAVA PROGRAMMING

Who has developed java?


Java was developed by James Gosling and his team, at Sun Microsystems of
USA in 1991.

1. Explain History of Java.


Java is a general-purpose, object-oriented programming language developed
by James Gosling and his team at Sun Microsystems of USA in 1991. Java was
designed for the development of software for consumer electronic devices like TVs,
VCRs and such other electronic machines. The development team modeled their new
language java on C and C++but they removed a number of features of C and C++ that
was considered as sources of problems and thus made java a really simple, reliable,

2|P age
portable, and powerful language.The following table shows some important
milestones in the development of java.

Year Development
1990 Sun Microsystems decided to develop a special software that could
be used to manipulate consumer electronic devices.
1991 The team announced a new language named “oak”.
1992 The team demonstrated the application of their new language to
control a list of home application using a hand-held device.
1993 The team came up with the idea of developing Web applets using the
new language.
1994 The team developed a Web-browser called “Hotjava”.
1995 “Oak” was renamed “java” due to some legal snags.

• Note: - Java programs are classified into two categories.


 Application Program (Programs which run in a stand alone system).
 Applet Program.
• An Applet can be executed using appletviewer application, which is a part of java
development kit (JDK).
2. What is Applets?
An applet is a special kind of java program that is designed to be transmitted
over the Internet and automatically executed by a java-compatible web browser.

3. List out some differences betweenApplication program and Applet program.

Application Program Applet Program


 Stand alone software applications  Applet programs are used in
written in the java language are Internet Application.
known as java application.
 Program execution starts from  No main() in Applet. Applet first
main(). invokes run() method in it’s life
cycle.
 Application programs can run any  Applets cannot run any programs
programs on the system. on the system.

 Required java compiler and  Required java compiler and java


Interpreter to execute application enable web browser.
program.
 Applets cannot read or write to the
 Application program can read and file system
write from or to a file.

4. Why java is pure object oriented?

3|P age
Java supports various features of an object oriented programming language
such as abstraction, encapsulation, Inheritance, polymorphism etc.
Java was developed by James Gosling at Sun Microsystems in the year 1991
and has been gaining popularity every since. Before java, the industries were using
the two main languages C and C++. C is simple, powerful and procedural language.
C++ is object oriented, but also more complex and requires great deal of overhead to
maintain the program. Both languages are machine-dependent, which means that C
and C++ programs only run on same environment. The program must be recompiled
on another environment for the compilation.
Java is inherited the power and flexibility from C language and object-
oriented features from C++ without the overhead. And also in java the complete code
we have to write inside a class and we can access the methods by creating an object of
their respective built-in classes. Hence we can say that “Java is fully Object -
Oriented”.

5. List out some differences between Java and C++.

CPP Java
1. CPP is the superset of C. 1. Java is the superset of c and cpp
2. CPP supports Operator 2. Java does not support.
overloading.
3. CPP supports Pointer. 3. Java does not support.
4. CPP supports Multiple 4. Java does not support it. In Java
Inheritance. Interface fulfill the same concept.
5. CPP supports global variable 5. Java does not support global
declaration. variables, every variable must be
declared within a class.
6. There is Header files in CPP. 6. Java has no Header files, only
Packages.

7. List out some differences between Java and C.

C Java
C is a Procedure oriented language. Java is pure Object oriented language
C includes goto, sizeof ,typedef keyword. Java does not support.
C supports Pointer. Java does not support.
C supports struct, union, enumdatatype. Java does not support these.
C supports global variable declaration. Java does not support global variables,
Every variable must be declared within a
class.
There is Header files in C. Java has no Header files, only Packages.
C supports preprocessor (macro). Java does not support preprocessor.

4|P age
8. What is OOP’s? Explain the features of OOP’s.

Object-oriented programming is an approach that provides a way of


modularizing programs by creating partitioned memory area for both data and
functions that can be used as templates for creating copies of such modules on
demand.

Some of the features of OOPS are...

 Programs are divided into what are known as Objects.


 Concentrate on Data rather than Procedure.
 Methods that operate on the data of an object are tied together in the
data structure. (Data Encapsulation)
 Data is hidden and cannot be accessed by external function.
 Objects may communicate with each other through methods.
(Message. communication).
 Follows bottom-up approach in program design.

9. Explain some applications of OOP’s

The promising areas for application of OOP includes

 Real time systems.


 Simulation and modeling.
 Object oriented databases.
 Artificial Intelligence and expert systems.
 Neural networks and parallel programming.
 Decision support systems
 CAD systems.

10. Explain the features of JAVA.

The Inventors of Java wanted the language to be not only reliable, portable
and distributed but also simple compact and interactive. Following are the features of
Java.

• Compiled and Interpreted.


 Java programs are first compiled and then interpreted.
 Java Compiler checks the error and converts the source
(.java) file to the corresponding Bytecode (.class) file.
 The Java virtual machine then interprets this bytecode file
into the machine code and executes it.

5|P age
 The java Interpreter can execute Bytecode directly on any
computer on JVM has been installed.

• Platform Independent.
 Program once, run anywhere. Java compiler converts the
source file (.java) to the corresponding class (Bytecode) file
which can be executed any other environment without
compiling the program again.
 Java program can be easily moved from one computer
system to another, anywhere and anytime.
 Changes and upgrades in operating systems, processors, and
system resources will not force any changes in java
programs.
• Portable.
 Potable refers to the ability of a program to run on any
platform without changing the source code.
 The programs developed on one computer can be run on
another computer.
 Java compiler converts source file to a bytecode file. The
bytecode can be executed on any platform.

• Object-Oriented.
 Java supports the object oriented approach to develop
programs.
 It supports various features of an object oriented
programming language such as abstraction, encapsulation,
Inheritance, polymorphism etc.
• Secure.
 Java is intended to work in network and distributed
environment by providing security.
 The absence of pointers in java ensures that programs
cannot gain access to memory locations without proper
authorization.
 Java compiler generates Bytecode instructions that can be
implemented on any machine. And also it is very secure
code.

• Distributed.
 Java is used to develop application that can be distributed
among various computers on the network.
 Java supports various Internet protocols, such as TCP, IP
etc.

6|P age
 Java application can open and access remote objects on the
internet.
• Simple and Small.
 Java is simple because there is no need for header files,
pointer arithmetic, structures, unions, operator
overloading, and virtual base class and so on.
 Also Java does not support Storage classes like auto,
register, extern etc.
 That is why java is simple and small.
• Multithreaded.
 Executing two or more sections of a program at the same
time is known as multithreading.
 Java supports multiple tasks to be executed
simultaneously.
 That is why java supports multithreaded concepts.
• High performance.
 Java programs are first compiled and interpreted.
 Java uses Just in time (JIT) compilation to speeds up the
execution process.

11. Why java is platform Independent? Or how java satisfies the portability? Or why java
is robust?

 Program once, run anywhere. Java compiler converts the source file(.java) to
the corresponding class (Bytecode) file which can be executed any other
environment without compiling the program again.
 Java program can be easily moved from one computer system to another,
anywhere and anytime.
 Changes and upgrades in operating systems, processors, and system resources
will not force any changes in java programs.
 Java compiler generates Bytecode instructions that can be implemented on
any machine. And also it is very secure code.
 The size of the primitive data types are machine independent.
 This is the reason why java has become a popular programming language.

12. Why java is secure?

 Security becomes an important issue for a language that is used for


programming on Internet.
 Java systems not only verify all memory access but also ensure that no viruses
are communicated with an applet.
 The absence of pointers in java ensures that programs cannot gain access to
memory locations without proper authorization.

7|P age
 Java compiler generates Bytecode instructions that can be implemented on any
machine. And also it is very secure code.

13. What is bytecode?


Bytecode is a highly optimized set of instructions designed to be executed by
the java run time system, which is called java virtual machine. JVM is an interpreter
for bytecode.

14. What is WWW?


 WWW stands for World Wide Web.
 The World Wide Web is a system of interlinked hypertext documents
accessed via internet.
 The World Wide Web allows computer users to locate and view multimedia-
based documents on almost any subject like multimedia, images, sounds,
animation etc.
15. What is W3C?
 W3C stands for World Wide Web consortium.
 The Berners-Lee founded W3C organization in 1994.
 W3C is a standardization organization which standardized the web
technologies.
 W3C recommendations include the
• XHTML (Extensible Hypertext Markup
Language).
• CSS (Cascading Style Sheets).
• HTML (Hypertext Markup Language).
• XML (Extensible Markup Language).

16. What is Web Browser?


 Web Browser is software which acts as a container to handle the web
pages.
 Web Browser allows retrieving the information spread across the internet
and displaying it on the user’s terminal using Hypertext Markup Language
(HTML).
 Some of the web browser which supports JVM…
• Internet Explorer 5.5, 6.x, 7.x.
• Netscape 4.7x, 6.2x, 7.
• Mozilla 1.4+.
• Firefox.

17. What is JDK?


 Java Development Kit is a collection of tools to execute Java program.
 These tools are used for developing and executing java Programs.
 Some important JDK tools are

8|P age
• Java: - Java interpreter, which executes the class file.
• Javac:- Java compiler, which translates source (.java) file to
class(Bytecode) file.
• Javah:- It produces header files.
• Jdb:- java debugger, which helps to find errors in the
program.
• Javap:- java Disassembler, which convert bytecode files into a
program description.
• Appletviewer:- It enables to run java applets.
18. What is API?
 There are two parts of java’s environment,
• JDK – Java development kit also known as software development
kit.
• JSL—java standard library which is known as application
program interface (API).
 API includes hundreds of built-in classes and methods grouped into several
packages.
 Some common packages are…….
• Java.lang:- It is the collection of classes & methods required for
implementing basic
features of java.
• Java.Io:- It is the collection of classes & methods required for
input/output
manipulation.
• Java.util:- It is the collection of classes & methods which
provides standard utility
functions like data and time.
• Java.applet:- It is the collection of classes & methods allow us to
create applet.
• Java.awt:- Abstract windows toolkit used for graphical user
interface.
• Java.net:- It is the collection of classes & methods required to
perform network
interface operation.

19. What is JVM?


 JVM stands for java virtual machine which exists only inside the computer
memory.
 The class file which is in the form of bytecode can be executed by JVM.
 JVM is an interpreter for Bytecode.

9|P age
 JVM uses different techniques to execute the bytecode. The major
components of JVM are..
• Class loader:- The class loader loads the class files which are
required by a program running in the memory.
• Execution Engine:- This component executes the Bytecode one
line after another.
• JIT(Just In Time) compiler:-
 The JIT compiler is used for compiling the bytecode
into executable code.
 Running the JIT compiled code is faster than running
the interpreted code because it is compiled and does
not require to be run, line by line.
20. What is JIT compiler?
 The JIT compiler is used for compiling the bytecode into executable code.
 Running the JIT compiled code is faster than running the interpreted code
because it is compiled and does not require to be run, line by line.

21. What is inheritance?


 Inheritance is a process by which one object of one class acquires the
properties of another object.
 Reusability is the one characteristics of Inheritance.

22. What is command Line argument?


 Command line arguments are parameters that are supplied to the
application program from the command prompt at the time of invoking
it for execution.
 Following program uses the command line arguments as input---

Class Comlineexample
{
Public static void main(String args[])
{
System.out.println(args[0]);
System.out.println(args[1]);
System.out.println(args[2]);
System.out.println(args[3]);

}
}

10 | P a g e
 After compiling the above program we will get Comlineexample.class
file.
 After getting the class file we can execute the program and at the same
time we have to pass four arguments.
 Then the arguments will be assigned to the array args[] as follows….

Java comlineexamplecobol network DBMS CPP

 After executing this line the array args[] become


Cobol------->args[0]
Network-- -->args[1]
DBMS-- -->args[2]
CPP-- -->args[3]

23. List out some methods of Math class.

 Java supports basic math functions through Math class defined in the
java.lang package.
 The math functions can be invoked by using the following syntax.

Math.functionname(parameter/parameters)
 Here, we are calling the function directly using the class name Math,
because these functions are static functions.
 Following table lists some math functions---

Function Action
sin(x) It returns the sine of the angle x in radians.
cos(x) It returns the cosine of the angle x in radians.
pow(x,y) It returns x raise y.
exp(x) It returns e raise x
log(x) It returns logarithm of x
sqrt(x) It returns square root of x
ceil(x) It returns the smallest whole number less than or equal to
x(rounding up)
floor(x) It returns the largest whole number les than or equal to x(rounded
down)
abs(x) It returns the absolute value of x
max(a,b) It returns the maximum value between a and b
min(a,b) It returns the minimum value between a and b

1. Explain the line “ public static void main(String args[])”

11 | P a g e
• Public: - The keyword public is an access specifier, that declares the main()
method as unprotected and therefore making it accessible to all other classes.
• Static: - Next appears the keyword static, which declares this method (main())
as one that belongs to the entire class and not a part of any objects of the
class. The main must always be declared as static since the interpreter uses
this method before any objects are created.
• Void: - The type modifier void states that the main method does not return
any value.
• Main():- The method main() is the starting point for the interpreter to begin
the execution of the program. A java application can have any number of
classes but only one of them must include a main method to initiate the
execution.
• String args[]:- args[] is a String object, which stores all the parameters
transferred from the command line at run time. i.e. command line arguments.
2. What is a comment?
 Comments are non executable statements (lines) i.e. the statements which
cannot be executed and compiled by the compiler
 Java permits both the single-line and multi-line comment comments.
 The single-line comments begin with // and end at the end of the line.
Eg: // program for addition
 For longer comments, we can create long multi-line comments by starting with
/* and ending with */
Eg: /* program for addition
Of two integers numbers */
3. Explain java TOKENs
 Smallest individual units in a program are known as tokens. The compiler
recognizes them for building up expressions and statements.
 In simple terms, a java program is a collection of Tokens, comments and white
spaces. Java language includes five types of token. They are..
• Reserved Keywords
• Identifiers
• Literals
• Operators
• Separators
 Reserved Keywords
• Keywords are some reserved words whose meaning can be
understandable by the compiler.
• Since keywords have specific meaning in java, we canot use
them as a variable, class, methods name.
• Java language has 60 reserved words.
• Examples:- abstract, Boolean, break, continue, throw, throws,
final, etc
 Identifiers

12 | P a g e
 Identifiers are programmer-designed tokens. They are used for
naming classes, methods, variables, objects, packages,
interfaces etc in a program
 Literals
 Literals in java are a sequence of characters (digits, letters, and
other characters) that represent constant values to be stored in
variables. Java supports five types of literals
 Integer literals: 20, 52, 102, 1, 3
 Floating-point literals: 5.5, 2.0, 3.3, 10.5
 Character literals: ‘a’, ‘m’, ‘v’, ‘2’
 String literals: “java”, “program”, “java program”,
“sum123”
 Boolean literals: true or false
 Operators
 An operator is a symbol that takes one or more arguments and
operates on them to produce a result
 Separators:
 Separators are symbols used to indicate where groups of code
are divided and arranged.
 E.g.: () {} [] ; , .
4. Explain constants in java
 Constants are programming element that does not change during the
execution of the program.
 Java supports several types of constants as illustrated in fig.

 Integer Constants:
• An integer constant refers to a sequence of digits. There are 3 types
of integer constants
a) Decimal integer: 123 -321 0 1519
b) Octal integer: 321 0435 551 0
c) Hexa-decimal integer: 0x2 0x551 0x 0x9AB (0x
indicates the integer is hexa-decimal, so 0x is
compulsory)
 Real Constants:
• The numbers with a decimal point are called as real or float
constants

13 | P a g e
• A floating point constant may contain four parts
I. A whole number
II. A decimal point
III. A fractional part
IV. An exponent
• E.g.: 5.65e4 1.5e+5 3.5
 Character Constants:
• A character constant contains a single character enclosed within a
pair of single quote
• E.g. ‘A’ ‘5’ ‘m’
 String Constants:
• A string constant is a sequence of characters enclosed between
double quotes. The characters may be alphabets, digits, special
characters and blank spaces.
• E.g.: “1982” “java” “well done” “x”
5. Explain all the Data types in java
 Data types specify the size and type of a variable.
 Data types in java under various categories are shown in fig.

• Java defines eight primitive types of data: byte, short, int, long, char, float,
double and boolean.
• Integer: Java defines four integer types: byte, short, int, and long. All of
these are signed, positive and negative values. Java does not support
unsigned integers.

Type Size(In Byte) Example


byte 1 byte b, c;
short 2 short s, t;
int 4 int a, b;

14 | P a g e
long 8 long days, distance;

• Floating-point numbers: Floating point numbers, also known as real


numbers, are used when evaluating expressions that require fractional
precision.

Type Size(In Byte) Example


float 4 float price, lowtemp;
double 8 double pi, r, a;

• Characters: In java, the data type used to store characters is char. Java uses
Unicode to represent characters. Unicode defines a fully international
character set. For this purpose it requires 16 bits (2 bytes).
e.g. char ch1, ch2;
• Booleans: Java has primitive types, called Boolean, for logical values. It
can have two values either true or false. This is the type returned by all
relational operators.
e.g.: boolean b1=false;
boolean b2=true;
• Java also supports some Non-primitive types of data: class, array and
interface.

6. Explain literals in java


 Literals in java are a sequence of characters (digits, letters, and
other characters) that represent constant values to be stored in
variables. Java supports five types of literals
 Integer literals: 20, 52, 102, 1, 3
 Floating-point literals: 5.5, 2.0, 3.3, 10.5
 Character literals: ‘a’, ‘m’, ‘v’, ‘2’
 String literals: “java”, “program”, “java program”,
“sum123”
 Boolean literals: true or false

7. Explain different types of operators in java.


 An operator is a symbol that tells the computer to perform certain
mathematical or logical manipulations.

15 | P a g e
 An operator is a symbol that takes one or more arguments and operates on
them to produce a result.
 Java operators can be classified into a number of related categories as
below...
1) Arithmetic operators
2) Relational operators
3) Logical operators
4) Assignment operators
5) Increment and
decrement operators
6) Conditional operators
7) Bitwise operators
8) Special operators

16 | P a g e
1) Arithmetic operators:
 The arithmetic operators are the operators that perform any basic form of
mathematic calculation. These include: addition, subtraction, multiplication,
division, and modulus.
Operator Usage Description Example
+ var1 + var2 Adds var1 and var2 int a=10, b=5;
C=a+b;
- var1 - var2 Subtracts var2 from int a=10, b=5;
var1 C=a-b;
* var1 * var2 Multiply var1 by var2 int a=10, b=5;
C=a*b;
/ var1 / var2 divide var1 by var2 int a=10, b=5;
C=a/b;
% var1 % var2 Computes remainder int a=10, b=5;
C=a % b;

2) Relational operators:
 Relational operators are used to compare two variables and determine the
relationship between them.
Operator Usage Description Example
> var1 > var2 Compare var1 and var2, return true if int a=10, b=5;
var1 is greater, else false if(a>b)
>= var1 > =var2 Compare var1 and var2, return true if int a=10, b=5;
var1 is greater than or equal to var2 while(a>=b)
< var1 < var2 Compare var1 and var2, return true if int a=5, b=10;
var1 is less than var2 if(a<b)
<= var1 <= var2 Compare var1 and var2, return true if int a=1, b=5;
var1 is less than or equal to var2 while(a<=b)
== var1 == var2 Compare var1 and var2, return true if int a=10, b=10;
var1 and var2 are equivalent if(a==b)
!= var1 != var2 Compare var1 and var2, return true if int a=10, b=5;
var1 and var2 are not equal if(a!=b)

3) Logical operators:
 The logical operators are used when we want to form compound conditions by
combining two or more relations.
Operator Meaning Description
&& Logical AND Condition1 && condition2 is true, if both the conditions are
true, false otherwise
|| Logical OR Condition1 && condition2 is false, if both the conditions are
false, true otherwise
! Logical NOT !(condition/conditions) is true, if inner condition is false.

4) Assignment operator:
 Assignment operator (=) is used to assign the value of an expression to a variable.
e.g.: var = expression; // Here the value of expression ( RHS)
will be assigned to var ( LHS ).

17 | P a g e
e.g.: x=y=z=100; // set x, y, z to 100.
5) Increment and Decrement operator:
 The ++ and the – are java’s increment and decrement operators.
 The increment operator increases its operand by one.
e.g. if a=10, then after executing the statement a++, a will be 11 .
So, a=a+1 and a++ both statements has same meaning.
 The decrement operator decreases its operand by one.
e.g. if a=10, then after executing the statement a--, a will be 9 .
So, a=a-1 and a-- both statements has same meaning.
6) Conditional operators:
 The symbol ?: is known as conditional operator.
 This operator is used to construct conditional expressions of the form
Exp1 ?Exp2 : Exp3
Where Exp1, Exp2, Exp3 are expressions.
 For example, consider the following example
a=10;
a=15;
x=(a>b) ? a : b;
In this example, x will be assigned the value of b. This can be achieved using the
if………….else statements as follows:

if(a>b)
x=a;
else
x=b;

7) Bitwise operators:
 These operators act upon the individual bits (long, int, short, char and byte) of
their operands.
 These operators are used for testing the bits or shifting them to the right or left.
 Bitwise operators may not be applied to float or double.
 They are summarized in the following table

Operator Meaning

& Bitwise AND

| Bitwise OR

~ Bitwise 1’s Complement

^ Bitwise XOR

<< Shift Left

>> Shift Right

18 | P a g e
 Bitwise Logical operators example
A B A|B A&B A^B ~A
0 0 0 0 0 1
1 0 1 0 1 0
0 1 1 0 1 1
1 1 1 1 0 0

 Bitwise Left Shift and Right Shift:


Operator Example Explanation
<< a=64; Shifting 2 bits towards left .
a=a<<2; result a=256
>> a=32; Shifting 2 bits towards right.
a=a>>2; Result= 8

8) Special operators:
 Java supports some special operators like instanceof operator and member
selection operator ( . ).
 E.g. personinstanceof student // is true if the object person belongs to the
class student, else it is false.
 E.g. personal.age // Reference to the variable age.
 E.g. personal.salary() // Reference to the method salary().

8. Explain different types of if statements.


 The if statement may be implemented in different forms depending on the conditions to
be tasted.
a) Simple if statement.
b) if….else statement.
c) Nested if…..else statement.
d) else……if ladder.
a) Simple if statement:
• The general form of a simple if statement is
if(test expression)
{
Statement/Statements;
}
• Here, if the test expression is true then the program control enters to the if block.
• For an example,
a=10; b=5;
if(a>b)
{
System.out.println(“a is greater”);
}

19 | P a g e
• In the above example the condition is true, so it will display “a is greater”
b) The if……else statement:
• The if…..else statement is an extension of the simple if statement. The general form is

if(test expression)
{
True-block statement/ statements;
}
else
{
False-block statement/statements;
}
• Here, if the test expression is true then program control enters to the True-block else
enters to the false-block.
• For an example,
a=5; b=10;
if(a>b)
{
System.out.println(“a is greater”);
}
else
{ System.out.println(“b is greater”); }
• In the above example the condition is false, so it will display “b is greater”
c) Nested if…else statement:
• When a series of decisions are involved, we may have to use more than one if-else
statement in nested form as follows.

if(test expression1)
{
if(test expression2)
{
Statement/Statements;
}
else
{
Statement/statements;
}
}
else
{
Statement/statements;
}
• In the above syntax, if test expression1 is true, then program control checks the test
expression2.
• For an example,
20 | P a g e
if(sex is female)
{
if(balance>5000)
{
Bonus=0.05*balance;
}
else
{
Bonus=0.02*balance;
}
}
else
{
Bonus=0.02*balance;
}
d) The else….if ladder:
• There is another way of putting when multipath decisions are invoked.
• A multipath decision is a chain of if’s in which the statement associated with each
else is an if. It takes the following form..

if(condition1)

Statement/Statements (1);

else if (condition2)

Statement/Statements (2);

else if (condition3)

Statement/Statements (3);

…………………………………………………………………

…………………………………………………………………

else if (condition n)

21 | P a g e
Statement/Statements (n);

else

Default Statement/Statements ;
}

• The above syntax known as Else ..If ladder. First condition1 will be checked. If it is false
program control checks the condition2. If condition2 is false program control checks the
condition3 and so on.

• For an example..

if(code==1)
{
color=”red”;
}
else if(code==2)

color=”green”;

else if (code==3)

color= “blue”;

else

color=”yellow”;

• In the above example, if code is 3, then the value of color will be “blue”.
• General Flowchart for if….else statement is as follows

22 | P a g e
Note: Java does not support goto statement…

1. Explain switch statement:


 So many multiple if…else statements in a single program increases the complexity of the
program. Java has a built-in multi-way decision statement known as switch.
 The switch statement tests the value of a variable (or expression) against a list of case
values and a match is found, a block of statements associated with that case is executed.
 The general form of the switch statement is as shown below:

switch(expression)
{
case value_1:
block1;
break;
case value_2:
block2;
break;
case value_3:
block3;
break;
………………….
………………………
casevalue_n:
block_n;
break;
default:
default-block;
break;
}

 The expression is an integer expression or characters. Value_1, value_2… are


constants or constant expressions and known as case labels.
 Each of these values should be unique within a switch statement.
 Block-1, block-2,… are statement lists and may contain zero or more statements.
 The default is an optional case.
 For an example,
……………………..

23 | P a g e
……………………..
index=marks/10;
switch(index)
{
case 10:
case 9:
case 8:
grade=”honours” ;
break;

case 7:
case 6:
grade=”First division”;
break;

case 5:
grade=”second sivision”;
break;
case 4:
grade=”third division”;
break;
default:
grade=fail;
break;
}
System.out.println(grade);

 So, depending upon the value of index, the corresponding case block will be
executed.

2. Explain different type of loops are available in java

 When a sequence of statements is executed repeatedly until some conditions for the
termination of the loop are satisfied, is called looping.
 Generally, A looping process would include the following four steps:
i. Initialization of a counter.
ii. Test for a specified condition.
iii. Execution of the statements in the loop.
iv. Incrementing the counter.
 There are four loops in java:
i. The for loop.
ii. The while loop.
iii. The do….while loop.
 For loop
 The general form of the for loop

for ( initialization; test condition; increment/decrement)


{
Body of the loop
}

 The execution of the for loop is as follows:

24 | P a g e
i. Initialize the control variable using assignment operator. Such as i=0;
count=1 etc.
ii. The value of the control variable is tested using the test condition.
Such as i<10; count<100 etc.
iii. If the condition is true, the body of the loop is executed; otherwise
the loop is terminated.
iv. After executing the body of the loop. Program control transfer back
to for statement and increase or decrease the control variable.
v. Again repeat the same process (from strep iii) until condition false.

 This execution process, we can show graphically as follows:

 For an example,

for(i=1; i<=10;i++)
{
System.out.println(i);
}

 So this loop will display 1 2 3 4 5 6 7 8 9 10.

 While loop:

 The basic format of the while loop is

Initialization;
while(test condition)
{
Body of the loop

Increment/decrement;
}
 The execution of the while loop is as follows:

25 | P a g e
a) Initialize the control variable using assignment operator. Such as i=0;
count=1 etc.
b) The value of the control variable is tested using the test condition.
Such as i<10; count<10 etc.
c) If the condition is true, the body of the loop will be executed. After
executing the loop body, the program control repeats the test
condition and executes the body of the loop if the condition is true.
d) This process continues until the condition become false.

 This execution process, we can show graphically as follows:

 For an example,

…………………….
……………………..
i=1;
while(i<=5)
{
System.out.println(i);
i++;
}

 So this loop will display 1 2 3 4 5

 Do…While Loop:
 The basic format of the do…while loop is

Initialization;
do
{
Body of the loop
Increment/decrement;
}while(test condition);
 The execution of the do…while loop is as follows:
 Initialize the control variable using assignment operator. Such as
i=0; count=1 etc.
26 | P a g e
 Program control enters to the body of the loop and executes the
statements.
 Then increase/decrease the control variable.
 Now it checks for the condition, if the condition is true, program
control again continues the execution of the body part of the loop.
 This process continues as long as condition is true. When the
condition become false. The loop will be terminated.
 Hence do..while loop test the condition at the end of the body part,
therefore, the body of the loop is always executed at least once.

 This execution process, we can show graphically as follows:

 For an example,
…………………….
……………………..
i=1;
do
{
System.out.println(i);
i++;
}while(i<=5)

 So this loop will display 1 2 3 4 5

3. Write the differences between while and do…while loop:

While Loop Do…..While Loop


Test the condition at beginning of the body of Test the condition at end of the body of the
the loop loop
Once the condition false loop terminates At entry time, even the condition false the
body of the loop will be executed at least
once

4. Explain break and continue statement with example:

27 | P a g e
• Break statement:

 An early exit from a loop can be accomplished by using the break statement.
 When the break statement is encountered inside any loop, the loop is immediately terminated
and the program continues with the next statement immediately following the loop.
 We can use the break statement inside any loop as well as inside switch statement for
separating the case blocks.
 For an example:

……………………….
……………………….
for(i=2;i<=20;i++)
{
for(j=2;j<i;j++)
{
if(i % j= =0)
break;
}
}
…………………………
…………………………
• Continue statement:
 Like the break statement, java supports another similar statement called the continue
statement.
 The continue causes, the loop to be continued with the next iteration after skipping any
statements in between.
 The continue statement tells the computer, “SKIP THE FOLLOWING
STATEMENTS AND CONTINUE WITH THE NEXT ITERATION”.
 The use of the continue statement in loops is illustrated as follows:

a) while(test condition)
{ ………….
……….. ..
if(condition)
Continue;
……………
……………
}
b) do
{
…………
if(codition)
continue;
………………..
………………..
}while(test condition);

c) for(initialization; test condition; increment/decrement)


{
………………
………………
if(condition)
28 | P a g e
Continue;
…………………
…………………
}

1. What is class? Explain with syntax and example:

 Class is a group of similar type of objects. Where object is the instance of a class.
 Class is a user-defined data type with a template that serves to define its properties.
 The basic form of a class definition is:

classclassname [extendsbaseclassname]
{
[Variable declaration;]
[Method declaration;]
}

Note: Everything inside square brackets ([ …… ]) is optional.


 Classname and baseclass name are any valid java identifiers.
 The keyword extends indicates that the properties of the baseclassname are extended to
the classsname.
 For an example:

class Rectangle
{
int width; // variable (data member or instance variable) declaration.
int length;

voidgetdata(int x, int y) // method declaration.


{
length=x;
width=y;
}
} // End of the class
 So, in the above example, Rectangle is the class name. width, length and getdata() are
three properties of the Rectangle class.

2. What is method (function)? How to declare a method?


 A method is a self contained block of program.
 A method is required to manipulating the data members, i.e. to perform some operations
on data members we need method.

29 | P a g e
 Methods are declared inside the body of the class but immediately after the declaration of
the data members.
 The general form of a method declaration is:

Type Methodname (parameter_list)


{
Method body;
}
 Method declarations have four basic parts:
• Return Type: what type of value, the method definition should return.
• Methodname: the name of the method.
• Parameter_list: A list of parameters to pass.
• Method body: This is the actual body of the method.
 For an example:

class Rectangle
{
int width; // variable (data member or instance variable) declaration.
int length;

voidgetdata(int x, int y) // method declaration.


{
length=x;
width=y;
}
} // End of the class
 In the above example:
• Return type is void.
• Method name is getdata().
• x and y are two integer type parameters.

3. Write a java program which illustrates passing parameters to a method:

 class Rectangle
{
int width; // variable (data member or instance variable) declaration.
int length;
int area;

voidgetdata(int x, int y) // method declaration.


{
length=x;
width=y;
}

voidrectarea() // method declaration


{
area= width*length;
System.out.println(“Area = ”+area);
}
} // End of the class

class Example
30 | P a g e
{
public static void main(String args[])
{
Rectangle ob = new Rectangle();//creating object ob of class rectangle
ob.getdata(2,5); // calling the first method
ob.rectarea(); // calling the second method
}
}// End of the main class
 In the above example, we have declare two methods getdata() and rectarea() inside the
class Rectangle.
 Object ob is invoking the methodgetdata() and at the same time it is passing two integer
parameters. Object ob is also calling the methodrectarea().

4. What is object? How to create an object in java? Explain with an example.

 An object is an instance of a class.


 An object is a variable of a particular class type.
 The general form of creating an object is as follows:

classnameobjectname = new classname( [parameter lists for constructor] );


note: content inside the square bracket is optional.
 For an example,
class Add
{
int a, b, c; // three data members

void calculation() // method declaration


{
a=10;
b=5;
c=a+b;
System.out.println(“Answer = ”+c);
}
} // End of the class.

class Example
{
public static void main(String args[])
{
Add ob1 = new Add() ; // creating the object ob1 of class Add
Ob1.calculation(); //object ob1 is invoking the method calculation()
} // End of main
} // end of main class

 In the above example, Add is a class and we have created one object ob1 of this class.
Class Add contains three data members a, b, c and one method calculation(). This program
is adding two variables a and b, After adding the variables the result stores in the variable
c. We are displaying the value of c as the output.

31 | P a g e
5. What is static data member, and static member function?

 static variable

• It is a variable which belongs to the class and not to object(instance)


• Static variables are initialized only once, at the start of the execution. These variables will be
initialized first, before the initialization of any instance variables
• A single copy to be shared by all instances of the class
• A static variable can be accessed directly by the class name and doesn’t need any object
• Syntax : <class-name>.<variable-name>

 static method

• It is a method which belongs to the class and not to the object(instance)


• A static method can access only static data. It can not access non-static data (instance variables)
• A static method can call only other static methods and can not call a non-static method from it.
• A static method can be accessed directly by the class name and doesn’t need any object
• Syntax : <class-name>.<method-name>
• A static method cannot refer to "this" or "super" keywords in anyway
.

Note: main method is static, since it must be accessible for an application to run, before any
instantiation takes place.
• For an example:

class Student
{
static int b; //initialized to zero only when class is loaded not for each object created.

Student() //Constructor incrementing static variable b


{
b++;
}

void showData()
{
System.out.println("Value of b = "+b);
}

static void increment() // static method


{
a++;
}
}
class Demo
{
public static void main(String args[])
{
Student s1 = new Student();

32 | P a g e
s1.showData();
Student s2 = new Student();
s2.showData();

Student.b=10; // accessing the static data member b


s1.showData();
s2.showData();

Student.increment(); // invoking the static method increment()


s1.showData();
s2.showData();
}
}

• In the above example, b is a static data member and that is accessed by the static method increment().
• Both static member b and static method increment can be accessed directly by using the class name
Student.

6. What is constructor? Explain with an example:

• A constructor is a special function whose name is same as the class name and does not have
any return type.
• Constructors are used to initialize the instance variables (data members) of an object.
• When we create a new instance (a new object) of a class using the new keyword,
a constructor for that class is called. I.e. Constructor can be invoked at the time of object
creation only.
• For an example:
class Demo
{
int value1,value2;
Demo() // constructor with no argument
{
value1 = 10;
value2 = 20;
System.out.println("Inside Constructor");
}
void display()
{
System.out.println("Value1 === "+value1);
System.out.println("Value2 === "+value2);
}
} // End of the Demo class
Class ConstructorExample
{

public static void main(String args[])


{
Demo d1 = new Demo(); // invoking the default constructor
d1.display();
}
}

33 | P a g e
7. Differences between methods and constructors.
• There is no return type for a constructor. But methods should have return type.
• There is no return statement in the body of the constructor. Methods can have the return statement.
• Method name should not be same as the class name. But constructor name should be same as the
class name.
• The first line of a constructor must either be a call on another constructor in the same class (using
this keyword), or a call on the super class constructor (using super keyword). If the first line is
neither of these, the compiler automatically inserts a call to the parameterless super class constructor.

8. What is Constructor overloading

 Constructor overloading is a technique in Java in which a class can have any number of
constructors that differ in parameter lists, but same name
 The compiler differentiates these constructors by taking into account the number of
parameters in the list and their type
 Example of valid constructors for the class Account are

Account(int a);
Account (int a, int b);
Account (String a, int b);
 For an Example:

class Demo
{
int value1, value2;

Demo() // 1. constructor without parameter(default constructor)


{
System.out.println("Inside 1st Constructor");
value1 = 10;
value2 = 20;
}

Demo(int a) // 2. constructor with one integer parameter


{
System.out.println("Inside 2nd Constructor");
value1 = a;
}

Demo(int a, int b) // 3. constructor with 2 integer parameters


{
value1 = a;
value2 = b;
System.out.println("Inside 3rd Constructor");
}

void display()
{
34 | P a g e
System.out.println("Value1 === "+value1);
System.out.println("Value2 === "+value2);
}
}

classConstructordemo
{
public static void main(String args[])
{
Demo d1 = new Demo(); // invoking constructor 1.
Demo d2 = new Demo(30); // invoking constructor 2.
Demo d3 = new Demo(30,40); // invoking constructor 3.
d1.display();
d2.display();
d3.display();
}
}

 In the above example, we are using 3 constructors with same name but different parameter of the
class Demo. Hence, this is constructor overloading.

9. What is inheritance? Explain all the inheritance in java with separate examples:

 Inheritance is the process by which objects of one class acquire the properties of objects of another
class.
 Inheritance is the capability of a class to use the properties and methods of another class while
adding its own functionality.
 The mechanism of deriving a new class from an old one is called inheritance.
 The old class is known as the base class or super class or parent class and the new one is called sub
class or derived class or child class.
 A derived class can be defined as follows:
Class subclassname extends superclassname
{
Variable declaration;
Method declaration;
}
 The keyword extends signifies that the properties of the superclassname are extended to the
subclassname.
 Inheritance may take different forms:
a) Single inheritance.
b) Multiple inheritance.
c) Hierarchical inheritance.
d) Multilevel inheritance.

a) Single inheritance:

 One class when it is derived from only one base class.


 Pictorial form of single inheritance.

35 | P a g e
 Here vehicle is the base class and car is the derived class.
 For an example:

class A // base class


{
int x;

void get()
{
x=10;
}

void Show()
{
System.out.println(x);

}
}

class B extends A // derived class


{
int y;

voidgetdata()
{
y=100;
}

void display()
{
System.out.println(x);
System.out.println(y);
}
}

class Example
{
public static void main(String args[])
{
B ob = new B(); //creating the object of derived class
ob.get(); // calling base class properties
ob.getdata(); // calling derived class properties
ob.show(); // calling base class properties
ob.display(); // calling derived class properties
}
}

b) Multiple inheritace:

 One class, when it is derived from two or more than two base class:
 Java does not support multiple inheritance.

36 | P a g e
 Same concept we can implement using interface concept in java.

c) Multilevel inheritance:

 One class, when it is derived from another derived class.


 Pictorial form of multilevel inheritance:

 Here RacingCar is derived from another derived class Car, which is derived
from Vehicle base class.
 For an example:

class A // base class


{
int x;
void getA()
{
x=10;
}

void showA()
{
System.out.println(x);

}
}

class B extends A // derived class


{
int y;

voidgetB()
{
y=100;
}

37 | P a g e
void showB()
{
System.out.println(x);
System.out.println(y);

}
}

class C extends B // another derived class


{
int z;

voidgetC()
{
z=200;
}
void showC()
{
System.out.println(x);
System.out.println(y);
System.out.println(z);

}
}

class Example
{
public static void main(String args[])
{
C ob = new C(); //creating the object of derived class
ob.getA(); // calling base class properties
ob.getB(); // calling 1st derived class properties
ob.getC(); // calling 2nd derived class properties
ob.showA(); // calling base class properties
ob.showB(); // calling 1st derived class properties
ob.showC() // calling 2nd derived class properties
}
}
d) Hierarchical inheritance:

 In hierarchical type of inheritance, one class is extended by many subclasses.


 It is one-to-many relationship.
 Pictorial representation:

Hierarchical inheritance
 For an example:

38 | P a g e
class Aves
{
publicvoid fly()
{
System.out.println("Generally, aves fly");
}
}
class Parrot extends Aves
{
publicvoid eat()
{
System.out.println("Parrot eats fruits and seeds");
}
}
class Vulture extends Aves
{
publicvoid vision()
{
System.out.println("Vulture can see from high altitudes");
}
}

publicclassFlyingCreatures
{
publicstaticvoid main(Stringargs[])
{ // all the following code is composition for FlyingCreatures
Parrot p1 =newParrot();
p1.eat();// calling its own member
p1.fly();
// calling super class member by inheritance
Vulture v1 =newVulture();
v1.vision();// calling its own member
v1.fly(); // calling super class member by inheritance
}
}

10. Explain super() method with an example


Or
Explain subclass constructor in java.

• A subclass constructor is used to construct the instance variables of both subclass and the
superclass.
• The subclass constructor uses the keyword super to invoke the constructor method of the
super class.
• Super may only be used within a subclass constructor method.

39 | P a g e
• The call to the superclass constructor must appear as the first statement within the subclass
constructor.
• The parameters in the super call must match the order and type of the instance variable
declared in the superclass.
• For an example:

class Room
{
int length, area1;
int breadth;
Room(int x, int y)
{
length=x;
breadth=y;
}
void area()
{
area1= length*breadth;
System.out.println(area1);
}
}
classBedRoom extends Room
{
int height, area2;
BedRoom(int x, int y, int z)
{
super(x,y); // parameter should match with base class constructor
height=z;
}
void volume()

Area2= height*length*breadth;
System.out.println(area2);

class Example

40 | P a g e
public static void main(String args[])

BedRoom room1 = new BedRoom(14, 12, 10);

room1.area(); // calling base class method

room1.volume(); // calling derived class method

11. What is final variable?


• A java variable can be declared using the keyword final. Then the final variable can be
assigned only once.
• A variable that is declared as final and not initialized is called a blank final variable. A blank
final variable forces the constructors to initialize it.

/* This Java Example shows how to declare and use final variable in

a java class.

*/

publicclassFinalVariableExample

publicstaticvoid main(String[]args)

/ * Final variables can be declared using final keyword.

* Once created and initialized, its value can not be changed.

*/

finalinthoursInDay=24;

//hoursInDay=12; //This statement will not compile. Value can't be changed.

System.out.println("Hours in 5 days = "+hoursInDay*5);

}
41 | P a g e
}

/*

Output would be

Hours in 5 days = 120

*/

12. What is final method?


• The method which is declared as final is called final method.
• A final method cannot be overridden by subclasses. i.e. Methods declared as final
cannot be overridden.
• For an example:
class Base
{
int x;
Base()
{
x=10;
}

final void show()


{
System.out.println(x);
}
}

class Derived extends Base


{
int y;
Derived()
{
y=20;
}
void show() // this is not valid. show() can not be overridden.
{
System.out.println(y);
}
}

13. What is final class?


42 | P a g e
• A class declared using final keyword is called final class.
• A final class cannot be extended. This is done for reasons of security and efficiency.
• All methods in a final class are implicitly final.
• For an example,
finalclass Base
{
int x;
Base()
{
x=10;
}
final void show()
{
System.out.println(x);
}
}

class Derived extends Base /// this is not possible because Base is a final class.
{
}

14. What is abstract method?

• An abstract method is a method that is declared without an implementation (without


braces, and followed by a semicolon), like this:

abstract void moveTo(double deltaX, double deltaY);

• The method can be implemented inside any derived class.


• The abstract methods should exists inside a abstract class.
• For an example;
abstract class GraphicObject
{
int x, y;
voidmoveTo(intnewX, intnewY) // non-abstract
{
...
}
abstract void draw(); // abstract method
abstract void resize(); // abstract method
}
15. What is abstract class?
• An abstract class is a class that is declared abstract.
• It may or may not include abstract methods.
• Abstract classes cannot be instantiated, but they can be subclassed.
• If a class includes abstract methods, the class itself must be declared as abstract.

43 | P a g e
• For an example:

abstract class GraphicObject


{
// declare fields
// declare non-abstract methods
abstract void draw();
}
• When an abstract class is subclassed, the subclass usually provides implementations
for all of the abstract methods in its parent class.
• We can write this class like this:

abstract class GraphicObject


{
int x, y;
...
voidmoveTo(intnewX, intnewY) // non-abstract
{
...
}
abstract void draw(); // abstract method
abstract void resize(); // abstract method
}

16. What is method overloading? Explain with an example:


• In Java it is possible to define two or more methods within the same class that share the same
name, as long as their parameter declarations are different.
• When this is the case, the methods are said to be overloaded, and the process is referred to
as method overloading.

• When an overloaded method is called, Java looks for a match between the arguments used to
call the method and the method's parameters.

• Here is a simple example that illustrates method overloading:

classOverloadDemo
{
void test() // method1 with name test.
{
System.out.println("No parameters");
44 | P a g e
}
void test(int a) // Overload test() for one integer parameter.
{
System.out.println("a: " + a);
}
void test(int a, int b) // Overload test for two integer parameters.
{
System.out.println("a and b: " + a + " " + b);
}
}

class Overload
{
public static void main(String args[])
{
OverloadDemoob = new OverloadDemo();
// call all versions of test()
ob.test(); //calling method1
ob.test(10); //calling method2
ob.test(10, 20); //calling method3
}
}
This program generates the following output:
No parameters
a: 10
a and b: 10 20

• As we can see, test( ) is overloaded three times. The first version takes no parameters, the
second takes one integer parameter, and the third takes two integer parameters.

17. What is method overriding? Explain with an example:


• In a class hierarchy, when a method in a subclass has the same name and type signature as a
method in its superclass, then the method in the subclass is said to override the method in the
superclass.
• For an example:
class A
{
inti, j;
A(int a, int b)
{
i = a;

45 | P a g e
j = b;
}
void show()
{
System.out.println("i and j: " + i + " " + j);
}
}

class B extends A
{
int k;
B(int a, int b, int c)
{
super(a, b);
k = c;
}
void show() // method override
{
System.out.println("k: " + k);
}
}

class Override
{
public static void main(String args[])
{
B subOb = new B(1, 2, 3);
subOb.show(); // this calls show() in B
}
}

The output produced by this program is shown here:


k: 3
• When show( ) is invoked on an object of type B, the version of show( ) defined within B is
used. That is, the version of show( ) inside B overrides the version declared in A.

• While overriding we have to fallow rules:


o In the overriding, the method names and the argument lists must be same.
o I.e. In the case of the overriding the signatures of the methods must be same
o The return types must be same.

Note: - This example you can use for super() method also.

46 | P a g e
18. What is array? How to declare one and two dimensional array in java? Explain with an example.

• An array is a collection of same type of data.


• An array is a group of contiguous or related data items that share a common name.
• An array can be declared and created in the computer memory before they are used.
• Creation of an array involves three steps:
1) Declare the array.
2) Create memory location.
3) Assign values into array.
1) Declare the array:
• Arrays in java may be declared in two forms:
Form1:
Type arrayname[ ]; // single dimensional
Type arrayname[ ][ ]; // two dimensional

Form2:

Type[ ] arrayname; // single dimensional

Type[ ] arrayname; // two dimensional

• Examples:
intarr[ ];
int[ ] arr;
floattdarr[ ][ ];
float[ ][ ] tdarr;
2) Creation of arrays:
• After declaring the array we need to create in the memory using new operator.
• Arrayname = new type[ size ]; // single dimensional
• Arrayname= new type [ row size] [col size]; // two dimensional
• For examples:
arr = new int[5] ; // array arr can hold 5 integers.
tdarr=new float [3][4]; // array tdarr has 3 rows and 4 cols.
3) Assign values into array:
• The final step is to put values into the array created.
• This can be done using the array subscripts as follows.

Arrayname[subscript]=value;
Arrayname[row number][col number]=value;

Example:
arr[2]=10;
arr[3]=20;

tdarr[1][2] = 30;
tdarr[2][1] = 30;

47 | P a g e
Note: it is also possible to combine the 1st and 2nd step together:

intarr[ ] = new int[ 5 ];

inttdarr[ ][ ] = new int[ 2 ][ 3 ];

19. How to initialize array injava?


• We can initialize arrays automatically in the same way as the ordinary variables when they
are declared, as shown below.

Type arrayname[ ] = { list of values }; // for single dimensional


Type arrayname[ ][ ] = { list of values }; for two dimensional

• Example:
intarr[ ] = { 10, 40, 20, 30, 50 };// for single dimensional

inttdarr[ ][ ] = {
{10, 20, 30 }, //for two dimensional
{ 5, 20, 10 },
{ 20, 10, 5 }
};

20. Write a java program which will accept elements in a single dimensional array.

import java.io.*;
classArrayExample
{
public static void main(String args[ ]) throws IOException
{
DataInputStream ds = new DataInputStream(System.in);
inti;
System.out.println(“Enter number of elements: ”);
int n = Integer.parseInt(ds.readLine());

int a[ ] = new int[n]; // array declaration

System.out.println(“Enter “ + n + “elements: ”); // accepting elements into array


for(i=0; i<n; i++)
a[i] = Integer.parseInt(ds.readLine());

System.out.println(“Elements are: ”); //displaying the elements


for(i=0; i<n; i++)
System.out.println(a[i]);

48 | P a g e
}

21. Write a java program which will accept elements in a two dimensional array.

import java.io.*;
classArrayExample
{
public static void main(String args[ ]) throws IOException
{
DataInputStream ds = new DataInputStream(System.in);
inti, j;
System.out.println(“Enter number of rows: ”);
int r = Integer.parseInt(ds.readLine());

System.out.println(“Enter number of cols: ”);


int c = Integer.parseInt(ds.readLine());

int a[ ] = new int[r][c]; // array declaration

System.out.println(“Enter elements: ”); // accepting elements into array


for(i=0; i<r; i++)
for(j=0; j<c; j++)
a[i][j] = Integer.parseInt(ds.readLine());

System.out.println(“Elements are: ”); //displaying the elements


for(i=0; i<n; i++)
for(j=0; j<c; j++)
System.out.println(a[i]);
}

22. What is vector? What are the methods are available in vector? Explain with an example:

• A vector can store objects of any type and any numbers.


• Vectors are commonly used instead of arrays, because they expand automatically when
new data is added to them.
• Vector class available inside the java.util package.
• The objects do not have to be homogenous.
• Vectors can be created as follows:

Vector vectorname = new Vector(); // declaring without size


Vector vectorname = new Vector(size); // with size
• Example:
49 | P a g e
Vector v1= new Vector();
Vector v2= new Vector(5);
• Some important vector methods are:

Methods Description
list.addElement(item) Adds the item at the end of the vector
list.elementAt(pos) Give the name of the object at that particular
position
list.size() Gives the number of objects
list.removeElement(item) Remove the specified item from the list
list.removeElementAt(n) Remove an item from nth position
list.removeAllElements() Remove all elements
list.insertElementAt(item, n) Inserts the item at nth position

• For an example

import java.util.*;
public class VectorDemo
{
public static void main(String[] args)
{
Vector vector = new Vector( );

int primitiveType = 10;


Integer wrapperType = new Integer(20);
String str = "tapan joshi";

vector.add(primitiveType);
vector.add(wrapperType);
vector.add(str);

vector.add(2, new Integer(30));

System.out.println("the elements of vector: " + vector);


System.out.println("The size of vector are: " + vector.size());
System.out.println("The elements at position 2 is: " + vector.elementAt(2));
System.out.println("The first element of vector is: " + vector.firstElement());
System.out.println("The last element of vector is: " + vector.lastElement());

vector.removeElementAt(2);

System.out.println("The elements of vector: " + vector);

}
}

1. What is interface? Why we need interface?


• In java, an interface is a concept like classes, which contain only abstract methods (The
method without body) and final variables (constant variable, i.e. value can not be altered).
50 | P a g e
• The general form of an interface is as follows:
interface interfacename
{
Variables declaration; // should be final
Methods declaration; // should be abstract
}
• For an example:
interface Item
{
static final int code =100; //final variable
static final String name = “Fan” ; //final variable
abstract void display(); // abstract class
}
• Therefore, classes are responsible to implements the interface for defining the function body.

• Java does not support multiple inheritances, but using interface we can implement the
concept of multiple inheritance.

2. How to extends the interface? Explain with an example.


• Like classes, interface can also be extended. That is, an interface can be sub interfaced from
other interfaces.
• The new sub interface will inherit all the properties of the super interface like classes.
• The general form for extending the interface is as follows:

interfacesubinterfacenameextendssuperinterfacename
{
Final variables;
Abstract methods;
}
• For an example we can keep all the final variables in the base interface and all the abstract
methods we can keep inside a derived interface is as follows:

interfaceItemconstants // base interface


{
staticint code = 100;
static String name = “pen”;
}

interface ItemextendsItemconstants // derived interface


{
Void display();
}
• In the above example The interface Item will inherit both the constants code and name into it
from the base interface Itemconstants.

3. How you can implement the abstract methods of an interface?


Or
How you can implement an interface?

• We know that all the methods inside an interface are in the form of abstract method. I.e. the
method which does not have any body implementation inside an interface.
• Therefore, it is the responsibility of the class that implements an interface to define the code
for implementation of these methods.
51 | P a g e
• This is done as follows:
classclassnameimplementsinterfacename
{
Body of the classname;
}
• Here the class classname “implements” the interface interfacename.
• A more general form of implementation may look like this:

classclassnameextendsbaseclassnameimplements interface1, interface2,…


{
Body of the classname;
}
• This shows that a class can extend another class while implementing interfaces.
• For an example:
interfaceItemconstants // base interface
{
staticint code = 100; // properties of base interface 1
static String name = “pen”;
}

interface Itemmethods // another interface


{
abstract void display(); // properties of base interface 2
}

interface Item extends Itemconstants, Itemmethods


{

// can use the properties of both interface1 and interface2

final static float cost=11.50; // derived interface properties


abstract void displaycost();
}

classItemclassimplements Item
{

void display() // implementing the abstract method display()


{
System.out.println(“Item code= ”+code);
System.out.println(“Item name= ”+name);
}

voiddisplaycost() // implementing the abstract method displaycost()


{
System.out.println(“Item cost= ”+code);
}
}
classProginterface

52 | P a g e
{
public static void main(String args[ ])
{
Itemclassob=new Itemclass();
Ob.display();
Ob.displaycost();
}
}

4. How interface is satisfying the concepts of multiple inheritances? Explain with an example.
• We can derive several interfaces into a single derived interface. I.e. One interface can have
more then one parent interfaces.
• Following program illustrating the same:

interfaceItemconstants // base interface


{
staticint code = 100; // properties of base interface 1
static String name = “pen”;
}

interface Itemmethods // another interface


{
abstract void display(); // properties of base interface 2
}

interface Item extends Itemconstants, Itemmethods


{

// can use the properties of both interface1 and interface2

final static float cost=11.50; // derived interface properties


abstract void displaycost();
}

classItemclassimplements Item
{

void display() // implementing the abstract method display()


{
System.out.println(“Item code= ”+code);
System.out.println(“Item name= ”+name);
}

voiddisplaycost() // implementing the abstract method displaycost()

53 | P a g e
{
System.out.println(“Item cost= ”+code);
}
}
classProginterface
{
public static void main(String args[ ])
{
Itemclassob=new Itemclass();
Ob.display();
Ob.displaycost();
}
}

5. What is the difference between class and interface?

Class Interface
A class may contain any type of data But one interface can contain only final
members and any type of member function variables and abstract methods.
including final variables and abstract
methods

One class can extends another class and can One interface can extends one or more than
implement interfaces one interfaces.

We can create a class using class keyword We can create an interface using interface
keyword

6. What is package? Why we need package? How many types of packages?

• Packages are java’s way of grouping a variety of classes and/or interfaces together.
• Packages act as “containers” for classes and interfaces.
• It is similar to “class libraries” in other languages.
• Following are the advantages of packages:
 We can reuse the classes available inside the packages.
 Two classes, in two different packages can have the same name.
 Package provides the mechanism for hiding the classes.
 Packages also provide a way for separating “design” and “code”.
• There are two categories of packages:
54 | P a g e
a) Java API packages.
b) User defined packages.
A. Java API packages:
 Java API (application program interface) provides a large number of classes
grouped into different packages according to the functionality.
 Most of the packages are available with the java API.
 Following are the some API packages.

JAVA

lang util io awt net applet



java.lang: this package includes: String, Math, Thread, Exception etc.

java.util: Includes Vectors, random numbers, Date etc.

java.io: includes DataInputStream, FileInputStream etc.

java.awt: includes Button, Label, Text, TextArea etc.

java.net: include classes for communication purpose.

Java.applet: include classes for creating and implementing applets.
B. Java user defined packages:
 The user can also able to create their own packages in java.
 The packages which are designed by user is known as user defined packages.
7. How you can import a package in your program?
Or
How you can access a package in your program?

 We use the keyword import to include a package in our program. The same procedure can
be used for both the types of packages, user defined as well as API packages.
 We can import a package using two way:
1) The first general form of import statement is as follows:

import package1 [. Package2 ] [. Package3 ] [ . package4 ] .classname

 Here package1 is the name of the top level package.


 Package2 is the name of the package that is inside the package1, and so on.
 We can have any number of packages in a package hierarchy.
 Finally, the explicit classname is specified.

2) The second general form of import statement is as follows:

import package1.*;
 Here the star ( * ) indicates that the compiler should search this entire hierarchy
when it encounters a class name.
 * includes all the classes available inside the specified package.
 For an example,
55 | P a g e
import java.io.*; // built in package.(API package)
importjava.lang.Math;

importmypack.*; // user defined package

8. How to create a user defined packages?

• We can create our own package in java.


• We must first declare the name of the package using the package keyword followed by a user
defined class name.
• Following example shows the implementation of a package:

packagemypackage; // package declaration

public class mypackageclass // class declaration


{
………………..
……………….. // body of the class
…………………

}
• Here mypackage is the package name and mypackageclassname is the part of mypackage
package.
• This program we should save inside a directory called mypackage using the name
mypackagename.java.and we have to compile it, to make the
mypackageclassname.classfile.
• So, to create a package we can follow the following steps:

Step1: declare the package at the beginning of a file, like this

package packageneme;

step2: Define the class that is to be put in the package and declare it as
public.
Step3: create a subdirectory under the main directory where the main source
Files are stored.
Step4: save the file using the classname.java in the created directory.
Step5: compile the file to generate the class file.

9. How to create a sub package?

• To create a sub package, first we have to create a main package. Then only we can create a
sub package under it.
• We can create a main package using these steps:
Step1: declare the package at the beginning of a file, like this
package packageneme;

step2: Define the class that is to be put in the package and declare it as

56 | P a g e
public.
Step3: create a subdirectory under the main directory where the main source
Files are stored.
Step4: save the file using the classname.java in the created directory.
Step5: compile the file to generate the class file.

• For Example, here we are creating one main package mypackage.


packagemypackage; // package declaration

public class mypackageclass // class declaration


{
………………..
……………….. // body of the class
}
• Now we can create a sub package using the following steps:
Step1: declare the package at the beginning of a file, like this
package mainpackageneme.subpackagename;

step2: Define the class that is to be put in the package and declare it as
public.
Step3: create a subdirectory subpackagename under the mainpackagename
directory .
Step4: save the file using the classname.java in the created directory.
Step5: compile the file to generate the class file.

• For Example, here we are creating one sub package mysubpackage.

packagemypackage.mysubpackage; //sub package declaration

public class mypackageclass // class declaration


{
………………..
……………….. // body of the class
}

10. What is error? Explain different types of error.


• Errors are the mistakes that can make a program go wrong.
• An error may produce an incorrect output or may terminates the program execution
abnormally or even may cause the system to crash.
• There are two types of error:
a) Compile-time error.
b) Run-time error.
a) Compile-time error:
• All the syntactical errors will be detected and display by the java compiler and therefore
these errors known as compile-time error.
• Compile time error may arise when...
 Missing semicolon (;).
 Missing brackets in classes or methods.
 Misspelling of identifiers and keywords.
 Missing double quotes in strings.
57 | P a g e
 Use of undeclared variables.
 And so on...
b) Run-time error:
• Run-time error may occur because of some logical mistake in the program.
• A program may compile successfully and generates the .class file but may not run
because of run-time error.
• Most common run-time errors are:

 Dividing an integer by zero.


 Accessing an element that is out of the bounds of an array.
 Trying to store a value into an array of incompatible type.
 Attempting to use a negative size for an array.
 Accessing a character that is out of bounds of a string.
 Reading characters from a close file.
 And many more.

11. What is exception? How to handle exception in java?
Or
Explain try, catch, throw, throws, finally.

 An exception is a problem that arises during the execution of a program. An exception can
occur for many different reasons, including the following:
• A user has entered invalid data.
• A file that needs to be opened cannot be found.
• A network connection has been lost in the middle of communications.
 Some of these exceptions are caused by user error, others by programmer error, and others
by physical resources that have failed in some manner.

 Java provides try catch, throw, throws and finally keywords for handling the exception.

try block:
 Java uses a keyword tryto preface a block of code that is likely to cause an error
condition.
 The try block can have one or more statements that could generate an exception.
 If any one statement generates an exception, the remaining statements in the block
are skipped.
 One try block should have at least one catch block or only one finally block.
catch block:
 A catch block defined by the keyword catch which catches the exception thrown by
the try block and handles it appropriately.
 The catch block is added just immediately after the try block.
 The catch statement is passed a parameter, which is reference to the exception object
thrown by the try block.
Finally block:
 The finally keyword is used to create a block of code that follows a try block. A
finally block of code always executes, whether or not an exception has occurred.
 finally block also may appears at the end of the catch blocks.
 Using a finally block allows you to run any cleanup-type statements that you want
to execute, no matter what happens in the protected code.

58 | P a g e
 The following are the different format of try-catch block:
Format1: try with a single catch block
try
{
statement/statements; // generates an exception.
}
catch(ExceptionName e1)
{
statement/statements; // process the exception.
}

Format2: try with multiple catch block


try
{
statement/statements; // generates an exception.
}
catch(ExceptionName e1)
{
statement/statements; // process the exception.
}
catch(ExceptionName e2)
{
statement/statements; // process the exception.
}
catch(ExceptionName e3)
{
statement/statements; // process the exception.
}
Format3: try with one finally block
try
{
statement/statements; // generates an exception.
}
finally
{
statement/statements; // process the uncaught exception.
}
Format4: try with multiple catch block and one finally block

try
{
statement/statements; // generates an exception.
}
catch(ExceptionName e1)
{
statement/statements; // process the exception.
}

59 | P a g e
catch(ExceptionName e2)
{
statement/statements; // process the exception.
}
catch(ExceptionName e3)
{
statement/statements; // process the exception.
}

finally
{
statement/statements; // process the uncaught exception.
}

 For an example:

// File Name : ExcepTest.java


import java.io.*;
public class ExcepTest
{
public static void main(String args[])
{
try
{
int a[] = new int[2];
System.out.println("Access element three :" + a[3]);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Exception thrown :" + e);
}
System.out.println("Out of the block");
}
}

throw:
 There may be times when we would like to throw our own exception. We can do this by
using the keyword throw as follows:

throw newthrowable-sublass();

 Example:

thrownew ArithmeticException();
thrownew NumberFormatException();

60 | P a g e
 Following example shows, how to create a user defined exception class.

import java.io.*;
importjava.lang.*;

classMyException extends Exception


{
MyException( String str )
{
super(str );
}
}

class Example
{
public static void main( String args[ ])
{
int x=5, y=1000;

try
{
float z = x / y;
if(z<0.001)
throw new MyException(“Number is too small”);
}
catch(MyException m)
{
System.out.println(“caught my exception”);
System.out.println(m.getMessage());
}
finally
{
System.out.println(“Thank you”);
}
}
}
throws:
 throws keyword is used to throw multiple exceptions.
 If a method does not handle a checked exception, the method must declare it using
the throws keyword.
 The throws keyword appears at the end of a method's signature.
 For an example:

import java.io.*;
public class className
{
public void withdraw(double amount) throws RemoteException,
InsufficientFundsException
{
// Method implementation

61 | P a g e
}
//Remainder of class definition
}

12. Explain class hierarchy of exception class:

Exception Hierarchy:
All exception classes are subtypes of the java.lang.Exception class. The exception class is a subclass
of the Throwable class. Other than the exception class there is another subclass called Error which is
derived from the Throwable class.
Errors are not normally trapped form the Java programs. These conditions normally happen in case
of severe failures, which are not handled by the java programs. Errors are generated to indicate errors
generated by the runtime environment. Example : JVM is out of Memory. Normally programs cannot
recover from errors.
The Exception class has two main subclasses :IOException class and RuntimeException Class.

Note the followings:

• A catch clause cannot exist without a try statement.


• It is not compulsory to have finally clauses when ever a try/catch block is present.
• The try block cannot be present without either catch clause or finally clause.
• Any code cannot be present in between the try, catch, finally blocks.

62 | P a g e
Lab exercises:

8. Program to calculate bonus for different department using method overriding.

//program to calculate bonus for different department using


method overriding

class base
{

63 | P a g e
int basic;
base(intsal)
{
basic=sal;
}
void show()
{
system.out.println("Basic Salary ="+basic);
}
}

class sales extends base


{
sales(intsal)
{
super sal;
}
void bonus_calc()
{
system.out.println("Bonus of sales dept ="+0.2*basic);
}
}

class purchase extends base


{
purchase(intsal)
{
super sal;
}
void bonus_calc()
{
system.out.println("Bonus of purchase dept
="+0.3*basic);
}
}
class hr extends base
{
hr(intsal)
{
super sal;
}
void bonus_calc()
{
system.out.println("Bonus of hrdept ="+0.5*basic);
}
}

class bonus
{
public static voidmain(String args[])
{
sales s= new sales(5000);
s.show();
s.bonus_calc();
64 | P a g e
purchase p= new purchase(5000);
p.show();
p.bonus_calc();

hr h= new hr(5000);
h.show();
h.bonus_calc();
}
}

9. Program to implement thread priorites.

//program to implement thread priorites

class A extends Thread


{
public void run()
{
system.out.println("Thread A starts");
for(inti=1; i<=5;i++)
{
system.out.println("Thread A inside"+i);
}
system.out.println("Thread A Existed");
}
}

class B extends Thread


{
public void run()
{
system.out.println("Thread B starts");
for(int j=1; j<=5;j++)
{
system.out.println("Thread B inside"+j);
}
system.out.println("Thread B Existed");
}
}
class C extends Thread
{
public void run()
{
system.out.println("Thread C starts");
for(int K=1; K<=5;K++)
{
system.out.println("Thread C inside"+K);
}
system.out.println("Thread C Existed");
}
}
65 | P a g e
class threadprior
{
public static voidmain(String args[])
{
A ob1=new A();
ob1.setPriority(Thread.MIN_PRIORITY);
ob1.start();

B ob2=new B();
ob2.setPriority(Thread.NORM_PRIORITY);
ob2.start();

C ob3=new C();
ob3.setPriority(Thread.MAX_PRIORITY);
ob3.start();
}
}

10. Program to implement keyboard events.

//program to implement keyboards events

importjava.awt.*;
importjava.awt.event.*;
importjava.applet.*;

public class keyevents extends Applet implements KeyListener


{
string str="";
public void init()
{
addKeyListener(this);
request Focus();
}
public void paint(Graphics g)
{
g.drawString("OUTPUT",10,15);
g.drawString(str,40,40);
}
public void keyPressed(KeyEventske)
{
showStatus("Key Pressed");
}
public void keyTyped(KeyEventske)
{
showStatus("Key Typed");
}
public void keyReleased(KeyEventske)
{
showStatus("Key Released");
}
66 | P a g e
}

keyevents.html

<html>
<body>
<applet
code="keyevents.class"
width=500
heigth=500>
</applet>
</body>
</html>

11. Program to implement mouse events.

//program to implement keyboards events

importjava.awt.*;
importjava.awt.event.*;
importjava.applet.*;
import java.awt.event.MouseEvent;

public class keyevents extends Applet implements


MouseListener, MouseMotionListener
{
string str="";
public void init()
{
addMouseListener(this);
addMouseMotionListener(this);
}
public void paint(Graphics g)
{
g.drawString(str,20,20);
}
public void mousePressed(MouseEvents me)
{
str="Mouse Button Pressed";
repaint();
}
public void mouseReleased(MouseEvents me)
{
str="Mouse Button Released";
repaint();
}
public void mouseClicked(MouseEvents me)
{
str="Mouse Button Clicked";
repaint();
}
67 | P a g e
public void mouseEntered(MouseEvents me)
{
str="Mouse Button Entered";
repaint();
}
public void mouseExited(MouseEvents me)
{
str="Mouse Button Exited";
repaint();
}
public void mouseMoved(MouseEvents me)
{
str="Mouse Button Moved";
repaint();
}
public void mouseDropped(MouseEvents me)
{
str="Mouse Button Dropped";
repaint();
}
public void mouseDragged(MouseEvents me)
{
str="Mouse Button Dragged";
repaint();
}

mouseevents.html
<html>
<body>
<applet
code="mouseevents.class"
width=500
heigth=500>
</applet>
</body>
</html>

12. Program to create student report using applet,read the input using textboxes and display the output
using buttons

13. Program to implement thread, applets, and graphics by implementing animation of ball moving.

//program to implement thread, applets and graphics

importjava.awt.*;
importjava.applet.*;

public class movingball extends Applet implements Runnable


{
int x=150,y=50,r=50;
68 | P a g e
int dx=11, dy=7;
Thread animator;
volatile booleanpleaseStop;

public void paint(Graphics g)


{
g.setColor(Color.red);
g.fillOval(x-r,y-r,r*2,r*2);
}

public void animation()


{
Rectangle bounds=getBounds();
if((x-r+dx<0)||(x+r+dx>bounds.width))
dx=-dy;
if((y-r+dy<0)||(y+r+dy>bounds.height)
{
dy=-dy;
x+=dx;
y+=dy;
repaint();
}
public vvoid run()
{
while(!pleaseStop)
{
animate();
try
{
Thread.sleep(100);
}
catch(InterruptedExpecction e)
{

}
}
}
public void start()
{
animator=new Thread(this);
pleaseStop=false;
animator.start();
}
public void stop()
{
pleaseStop=true;
}
}
}

movingball.html

69 | P a g e
<html>
<body>
<applet
code="movingball.class"
width=500
height=500>
</applet>
</body>
</html>

//program to create student report

importjava.awt.*;
importjava.awt.event.*;
importjava.applet.*;

public class studreport extends Applet implements ActionListener


{
Label lblTitle, lblRegno, lblCourse, lblSem, lblSub1, lblSub2;
TextFieldtxtRegno, txtSem, txtSub1, txtSub2;
Button cmdReport;
String rno="",course="",sem="", sub1="", sub2="", avg="", heading="";

70 | P a g e
public void init()
{
GridBagLayoutgbag=new GridBagLayout();
GridBagConstrainsgbc=new GridBagConstrains();
setLayout(gbag);
lblTitle=new Label("Fill the student Details:");
lblRegno=new Label("Register Number:");
txtRegno=new TextField(25);
lblSem=new Label("Semester:");
txtSem=new TextField(25);
lblCourse=new Label("Course:");
txtCourse=new TextField(25);
lblSub1=new Label("Subject 1 marks:");
txtSub1=new TextField(25);
lblSub2=new Label("Subject 2 marks:");
txtSub2=new TextField(25);
cmdReport=new Button("View Report");
gbc.weighty=1.0;
gbc.gridwidth=GridBagConstraints.REMAINDER;
gbc.anchor=GridBagconstraints.NORTH;
gbag.setConstraints(lblRegno,gbc);
}

studreport.html

<html>
<body>
<applet
code="studreport.class"
width=500
height=500>
</applet>
</body>
</html>

71 | P a g e

You might also like