Java Notes
Java Notes
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.
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”.
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.
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.
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.
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.
7|P age
Java compiler generates Bytecode instructions that can be implemented on any
machine. And also it is very secure code.
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.
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.
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 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
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.
14 | P a g e
long 8 long days, distance;
• 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.
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 OR
^ Bitwise XOR
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
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().
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…
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;
}
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.
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
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.
For an example,
for(i=1; i<=10;i++)
{
System.out.println(i);
}
While loop:
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.
For an example,
…………………….
……………………..
i=1;
while(i<=5)
{
System.out.println(i);
i++;
}
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.
For an example,
…………………….
……………………..
i=1;
do
{
System.out.println(i);
i++;
}while(i<=5)
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);
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;]
}
class Rectangle
{
int width; // variable (data member or instance variable) declaration.
int length;
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:
class Rectangle
{
int width; // variable (data member or instance variable) declaration.
int length;
class Rectangle
{
int width; // variable (data member or instance variable) declaration.
int length;
int area;
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().
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
static method
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.
void showData()
{
System.out.println("Value of b = "+b);
}
32 | P a g e
s1.showData();
Student s2 = new Student();
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.
• 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
{
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.
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;
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:
35 | P a g e
Here vehicle is the base class and car is the derived class.
For an example:
void get()
{
x=10;
}
void Show()
{
System.out.println(x);
}
}
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:
Here RacingCar is derived from another derived class Car, which is derived
from Vehicle base class.
For an example:
void showA()
{
System.out.println(x);
}
}
voidgetB()
{
y=100;
}
37 | P a g e
void showB()
{
System.out.println(x);
System.out.println(y);
}
}
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:
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
}
}
• 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[])
/* This Java Example shows how to declare and use final variable in
a java class.
*/
publicclassFinalVariableExample
publicstaticvoid main(String[]args)
*/
finalinthoursInDay=24;
}
41 | P a g e
}
/*
Output would be
*/
class Derived extends Base /// this is not possible because Base is a final class.
{
}
43 | P a g e
• For an example:
• When an overloaded method is called, Java looks for a match between the arguments used to
call the method and the method's parameters.
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.
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
}
}
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.
Form2:
• 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:
• 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());
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());
22. What is vector? What are the methods are available in vector? Explain with an example:
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( );
vector.add(primitiveType);
vector.add(wrapperType);
vector.add(str);
vector.removeElementAt(2);
}
}
• Java does not support multiple inheritances, but using interface we can implement the
concept of multiple inheritance.
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:
• 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:
classItemclassimplements Item
{
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:
classItemclassimplements Item
{
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();
}
}
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
• 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
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.*;
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;
}
• 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:
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.
• 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.
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.
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.
}
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:
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.*;
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
}
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.
62 | P a g e
Lab exercises:
class base
{
63 | P a g e
int basic;
base(intsal)
{
basic=sal;
}
void show()
{
system.out.println("Basic Salary ="+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();
}
}
B ob2=new B();
ob2.setPriority(Thread.NORM_PRIORITY);
ob2.start();
C ob3=new C();
ob3.setPriority(Thread.MAX_PRIORITY);
ob3.start();
}
}
importjava.awt.*;
importjava.awt.event.*;
importjava.applet.*;
keyevents.html
<html>
<body>
<applet
code="keyevents.class"
width=500
heigth=500>
</applet>
</body>
</html>
importjava.awt.*;
importjava.awt.event.*;
importjava.applet.*;
import java.awt.event.MouseEvent;
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.
importjava.awt.*;
importjava.applet.*;
}
}
}
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>
importjava.awt.*;
importjava.awt.event.*;
importjava.applet.*;
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