Java Notes
Java Notes
Java Notes
Chapter- 1
Introduction to Java
1) What is Java? Explain the features of java. [2012, 2013, 2015, 2016]
Ans:- Java is pure object-oriented & high level programming language developed by „Sun-
Microsystems‟ USA in 1991. Java is high level programming language, which consists of
objects & classes.
Features of Java
i) Java is Simple:- Java was developed by taking the best points from other programming
languages, primarily C and C+ +.
- Error tasks such as pointers and memory management have either been eliminated or are
handled by the Java environment automatically rather than by the programmer.
- Since Java is primarily a derivative of C + +.
iv) Java is Platform independent: It means we can run write & compile the java code in
one platform (eg: windows) and can execute in any other supported platform.
(eg: Linux, sun solaries etc.)
v) Java is Interpreted: - When Java code is compiled, the compiler outputs the Java Byte
code which is an executable for the Java Virtual Machine.
- The Java Virtual Machine does not exist physically but is the specification for a
hypothetical processor that can run Java code.
- Java interpreter generates machines code that can be directly executed by the machine
that is running Java program.
vi) Java is Robust and Secure:- Java is robust language. It provides many safeguards to
ensure reliable code.
- It has strict compile-time & run-time checking for data types.
- Java manages memory automatically by using an automatic garbage collector.
- The garbage collector runs as a low priority thread in the background keeping track of all
objects and references to those objects in a Java program.
1
Written By: Sunil, Mahesh, Nitin
Internet Programming
Security: Java systems not verify all memory access but also ensure that no viruses are
communicated through an applet.
- The absence of pointers in java ensures that programmer cannot give access to memory
locations without proper authorization.
- Java compiler produce only correct java code, there is still possibility of the code being
tampered between compilation & runtime.
vii) Java is Architecturally Neutral: - The Java compiler compiles source code to a stage
which is intermediate between source and native machine code.
- This intermediate stage is known as the byte code, which is known as neutral.
- The byte-code conforms to the specification of hypothetical machine called „java virtual
machine.
viii) Java is Portable: - Java ensures portability in two ways. Java compiler generator byte
codes instructions that can be implemented on any machine.
- By porting an interpreter for the Java Virtual Machine to any computer hardware/
operating system, one is assured that all code compiled for it will run on that system. This
forms the basis for Java's portability.
ix) Multithreaded and interactive: - Java supports developing programmes that handle
multiple tasks simultaneously. This feature improves the interactive performance of
graphical system.
- Java run-time comes with tools that support multiprocessor synchronization and
constructs smoothly running interactive system.
2
Written By: Sunil, Mahesh, Nitin
Internet Programming
They include:-
1) javac:- The javac compiler is used to compile the java source code files into byte
codes.
2) Java interpreter: - The java interpreter is used to execute java byte codes. It takes as an
argument the, name of the class file to execute or the name java archive file (jar).
3) appletviewer:- applet viewer is used for viewing java applets. It enables us to test java
applets without using web browsers.
4) java (java disassembles):- java converts byte code file into program description.
5) javah:- It produces header files for use with native network.
6) javadoc:- Creates html documentation from java source file.
a) Comments in java:- This are not executable statements, which returns for programmers
reference but not for program reference.
In java we can have two types,
1) // it is used for single line commenting
Ex: // this line commented.
2) /* */ used for multiline commenting.
Ex:- /* java is difficult */
b) Import statements: - java doesn't support header files like C. Java provides another
way of accessing the recourses which are stored in separate files in different packages by
importing the packages we can refer the classes, methods in our program.
- We can write as many as import statements.
Ex :- import ABCD.*; //means import all classes from package ABCD import ABCD.
tjava.*; //means import only java class of package EEPB.
}
}
public static void main(String args[ ]):- Java uses bit different type of the main method
public :- public is an access specifier if we declare any method as public it is globally
accessible.
Static:- Java is pure object oriented programming if we want to use any method
compulsory we have to create.
void :- It is a keyword returns nothing.
Main:- Here all programs execution starts from main only.
String args [] :- It is command line argument list sent t the method main at run time.
5types of Tokens:-
a) Keywords:- Keywords are predefined or reserved words have a specific feature that is
defined in the programming language.
- Keywords, operators, separators combined together forms a java program.
- The Java language has a rich set of keywords i.e. 53.
b) Identifiers:- Are names to refer the program objects in other words identifiers are user
defined tokens.
- They are used in naming the classes, variables, methods, objects, packages, interfaces in
the program.
- While choosing identifies the following rules to be maintained.
a) Identifiers may be alphabetic or alphanumeric but not numeric.
b) Identifier should not start from the number.
c) They should not be keywords.
4
Written By: Sunil, Mahesh, Nitin
Internet Programming
Ex: Invalid Identifiers: la, avg#, try, 123, roll-no Valid Identifiers: al, Avg, try, ABC,
roll_name.
c) Literals:- The compiler needs to translate the character strings "3.1" and "43" into
numerical values of a particular type.
- Such explicit values in a computer language are called "liberals" for the obvious reason
that they are literally equivalent to their stated value.
- Java supports 4 types of Literals:-
a) Floating Point Literals b) Integer Literals c) Characters and String Literals
d) Special Literals.
e) Separators: - Separators are symbols which divide our program into groups even they
help in arranging the code. Separators in Java
; Semi-colon indicates the end of a statement.
( ) Parentheses used in several places including:-
{} Curly braces: - enclose the fields and methods of a class.
[] Array declaration:- array specification.
5
Written By: Sunil, Mahesh, Nitin
Internet Programming
2) Class Variables (Static Fields): - a class variable is any field declared with the static
modifier; this tells the compiler that there is exactly one copy of this variable in existence;
regardless of how many times the class has been instantiated.
3) Local Variables:- Similar to how an object stores its state in fields, a method will often
store its temporary state in local variables.
- The syntax for declaring a local variable is similar to declaring a field (for example, int
count = 0 ;)
- There is no special keyword designating a variable as local; that determination comes
entirely from the location in which the variable is declared.
ii) Short: - The short data type is a 16-bit signed two's complement integer.
- It has a minimum value of -32,768 and a maximum value of 32,767.
iii) Int: - The int data type is a 32-bit signed two's complement integer.
- It has a minimum value of -2,147,483,648 and a maximum value of 2, 147, 483, 64.
iv) Long: - The long data type is a 64-bit signed two's complement integer.
- It has a minimum value of -9,223,372,036,854,775,808 and a maximum value of
9, 223, 372, 036, 854, 775, 807.
v) Float: - The float data type is a single-precision 32-bit floating point. As with the
recommendations for byte and short, use a float (instead of double) if you need to save
memory in large arrays of floating point numbers.
vi) Double: - The double data type is a double-precision 64-bit floating point. Its rang of
values is for decimal values, this data type is generally the default choice.
vii) Boolean: - The Boolean data type has only two possible values: true and false. t this
data type for simple flags that track true/false conditions.
6
Written By: Sunil, Mahesh, Nitin
Internet Programming
a) Integer constants: This are may be decimal or hexadecimal. This can range in
magnitude from negative to positive 231-1. Constants larger than these permissible
magnitudes will produce unpredictable results.
ex: 037, 0 0435. 0551
b) Real Constants:- Quantities are represented by number containing fractional parts like
17.543. Such numbers are called as „Real constants‟
- A real number may also be expressed in exponential notation.
For example: The value of 215.65 may be written as 2.1565e2 in exponential notation. E2
means multiply by 102.
General Form is: mantissa e exponent
Declaration of variables
- In Java, variables are the names of storage locations. After designing variable names, we
must declare to the compiler.
Chapter-2
Operators and Expressions
ii) The Relational Operators: These operators are used to check the Condition.
2) != (not equal to) Checks if the values of two operands are equal or (A != B) is
not. true.
3)> (greater than) Checks if the value of left operand is greater than (A > B) is
the value of right operand, if yes then condition not true.
becomes true.
4)< (less than) Checks if the value of left operand is less than the (A < B) is
value of right operand, if yes then condition not true.
becomes true.
5)>= (greater than Checks if the value of left operand is greater than (A >= B) is
or equal to) or equal to the value of right operand, if yes then not true.
condition becomes true.
8
Written By: Sunil, Mahesh, Nitin
Internet Programming
3) ! (logical not) Use to reverses the logical state of its !(A && B) is true
operand. If a condition is true then Logical
NOT operator will make false.
9
Written By: Sunil, Mahesh, Nitin
Internet Programming
Chapter – 3
Decision Making and Branching
4) NESTED IF STATEMENT
- If statement within another if statement is referred to as Nested If.
Syntax:-
if ( <<condition>> )
{
if ( <<condition>> )
{
Statements;
}
else
{
Statements;
}}
Else {
{
Statements; }
}
- Using the conditional operator you can rewrite the above example in a single line like this
max = (a > b) ? a : b;
(a > b) a: b;
- Here, is an expression which returns one of two values a or b.
- The condition, (a > b) is tested. If it is true the first value, a, is returned. If it is false, the
second value, b, is returned.
- Whichever value is returned is dependent on the conditional test, a > b. The condition can
be any expression which returns a Boolean value.
For example:
/* The programfind biggest of two numbers using? : Operator*/
class Big
{
public static void main(String args[])
{
int a=20,b=30;
string res="";
res= a>b ? "A is Greater" : "B is Greater";
System.out.println(res);
}
}
Example:
Program to print 1 to 10 using while loop:
class number
{
public static void main(String[] args)
{
int count = 1;
while (count < 11)
{
12
Written By: Sunil, Mahesh, Nitin
Internet Programming
2) DO WHILE LOOP
- It is Similar to the while statement, the do-while statement is a loop statement provided
by Java.
- The difference between the do-while statement and the while statement is that in the
while statement, the loop body is executed only when the condition stated in the statement
is true. In contrast, in the do-while loop, the loop body is executed at least once.
Syntax:- Example:-
do Program to print 1 to 5 using do while:
{ class number
Statements; {
While (condition); public static void main(String[] args)
} {
int n=0;
- Each iteration of the do-while loop first Do
executes the body of loop. {
Systems.out.println(n);
n++;
}
While (n<=5)
}}
3) FOR LOOP:- The for statement provides a compact way to iterate over a range of
values.
- Programmers often refer to it as the "for loop" because of the way in which it repeatedly
loops until a particular condition is satisfied.
Syntax:
for (initialization; termination; increment)
{
Statements;
}
JUMPING STATEMENTS
a) The break statement
- The break statement has two forms:- labeled and unlabeled. We can also use an unlabeled
break to terminate a for, while, or do-while loop, as shown in the following program
Example:-
Program to demonstrate Break statement:
Class sample
{
public static void main(String[] args)
13
Written By: Sunil, Mahesh, Nitin
Internet Programming
{
For(int i=1; i<=10; i++)
{
If(i==5)
Break;
System.out.println(i);
}
}
}
b) The continue statement:- It skips current iteration of for, while, or do-while loop. The
unlabeled form skips to end of the innermost loop‟s body.
- it evaluates Boolean expressions that controls the loop.
Example:-
Program to demonstrate Break statement:
Class sample
{
public static void main(String[] args)
{
For (int i=1; i<=10; i++)
{
If (i%2==0)
Continue;
System.out.println(i);
}
}
}
14
Written By: Sunil, Mahesh, Nitin
Internet Programming
Chapter -4
Packages and interfaces
15
Written By: Sunil, Mahesh, Nitin
Internet Programming
- The package P1 contains one public class by name. Suppose we want to add another class
B to this package. This can be as follows:
1) Define the class and make it public.
Package P1
Public class B
{
// body of B
}
16
Written By: Sunil, Mahesh, Nitin
Internet Programming
Chapter-5
Interfaces
Extending Interfaces:-
- One interface can inherit another by the use of keyword extends.
- When class implements an interface that inherits another interface.
17
Written By: Sunil, Mahesh, Nitin
Internet Programming
Chapter -6
Threads
1) What is thread?
Ans:- A thread is a sequential flow of control within a program. It is a fundamental unit of
program execution.
2) What is multithreading?
Ans:- The program containing two or more parts that can run concurrently is known as
multithreading.
- On other hand, multithreading is ability of a single program to perform more than one
task at same time called multithreading. Each part is called „Thread‟.
18
Written By: Sunil, Mahesh, Nitin
Internet Programming
b) Blocking: - Threads can be blocked temporarily from entering into the runnable.
1. sleep():- Blocked for specified time.
2. suspend():- Blocked until further orders.
3. wait() :- Blocked until certain condition occurs.
- When a thread creates new thread, it is merely empty thread object. No system resources
have been allocated for it.
- Calling any method besides start or stop when a thread in this state makes no sense and
couses an „IllegealThreadStateException‟.
3) Blocked State:- A Thread become Block, when one of these events occurs:
a) Someone invokes its sleep method.
b) Someone invokes its suspend method.
c) The thread uses its wait method to wait.
Example:- try{
Thread.sleep(1000);
}
catch (InterruptedExceptionc e)
{
}
- During the 10 seconds that myThread is asleep; even if processor becomes available
myThread does not run. After 10 seconds are up, my Thread becomes runnable again.
4) Dead State:- A thread can died in 2 ways; either from natural cases, or by being
killed(stopped).
- A thread dies natural when its run method exists normally.
Syntax:- public void run()
{
Int i=0;
While (i<100)
{
i++;
System.out.println(“i=”+i);
} }
- A thread with this run method dies naturally after the loop and run method complete.
myThread.stop():- The stop method throws a ThreadDeath object at thread to kill it.
- The thread will die when it actually receives the ThreadDeath exception.
20
Written By: Sunil, Mahesh, Nitin
Internet Programming
- Threads with higher priority are more important to program and should be allocated
processor time before lower priority threads.
Program example for Thread Priority:- {
Class A extends Thread for(int k=1;k=0;k++)
{ {
public void run() System.out.println(“k=”+k);
{ }
for(int i=1;i<=0;i++) }}
{ class ThreadPrior
System.out.println(“i=”+i); {
} public static void main(String args[])
}} {
class B extends Thread A thA=new A();
{ B thA=new B();
public void run() C thA=new C();
{ thA.SetPriority(1);
for(int j=1;j=0;j++) thB.SetPriority(3);
{ thC.SetPriority(9);
System.out.println(“j=”+j); thA.start();
} thB.start();
} thC.start();
} System.out.println(“End of main”);
class C extends Thread }
{ }
public void run()
21
Written By: Sunil, Mahesh, Nitin
Internet Programming
22
Written By: Sunil, Mahesh, Nitin
Internet Programming
Chapter – 7
Exception Handling
2) What are the types of errors? And explain briefly the error handling in java.
Ans:- Error may produce incorrect output or may terminate the execution of program or
may cause system to crash.
2 types of Errors:
1) Compile time error: - Compile time errors are all syntax errors detected & displayed
by the java compiler. Whenever the compiler displays an error, it will create the .class file.
- Most Compile time errors are ‘Missing Semicolon, braces’.
2) Run time error:- A program may compile successfully by creating the .class file.
However, it may not run properly. Such produce wrong results due to wrong logic or due
to errors.
- Most run time errors are ‘dividing the integer by Zero’.
23
Written By: Sunil, Mahesh, Nitin
Internet Programming
Catch Block:- A catch block catches the exception thrown by the try block & handles it
properly. The catch is added immediately after the try block.
- The catch block can have one or more statements that are necessary to process the
exception.
Syntax:- catch ( Exception type1)
{
--------------
-------------- }
class arithematicException
{
24
Written By: Sunil, Mahesh, Nitin
Internet Programming
Finally Block:- Java supports another statement finally that can be used to handle an
exception that is not caught by any of previous catch statements.
- Finally block can be used to handle any exception generated within try block.
- Finally block creates its own reason to leave by executing break or return or by throwing
an exception.
- Finally creates a block of code that will be executed after a try/catch block.
Syntax:- finally
{
----------
-----------
Statements
}
system.out.println(“Executing”);
}
}
}
26
Written By: Sunil, Mahesh, Nitin
Internet Programming
- The flow of execution stops immediately after throw statement. The nearest enclosing try
block is inspected to see if it has a catch statement that matches type of exception. If it
does, control is transferred to that statement. If not, then next enclosing try statement is
inspected and so on...
- Throw statement used explicitly throw an exception.
b) Throws: if a method is capable of causing a exception that it doesn‟t handle, this must
specify this behaviour so that caller of that method can guard themselves against that
exception. For this we use throws clause.
General Syntax:
type method-name(parameter-list) throws exception-list
{
// body of method
}
- Here, exception list is comma-separated list of exception that a method can throw.
27
Written By: Sunil, Mahesh, Nitin
Internet Programming
28
Written By: Sunil, Mahesh, Nitin
Internet Programming
Chapter – 8
Applet Programming
Types of Applets:
a) Local Applet:- An applet developed locally and stored in local system called local
Applet. When web page trying to find local applet, it doesn‟t need to use internet.
- It simply searches the directories on the local system.
29
Written By: Sunil, Mahesh, Nitin
Internet Programming
start()
stop()
Exit of Browser
i) Born State:- When the class is executed the init() function is automatically invoked. At
this stage applet is said to be born. This state is also called initialization state.
- During applet life cycle, the born state occurs only once in applet‟s life cycle.
- it is achieved by calling init() method of applet class.
Public void init() {-------------------}
ii) Running state:- Applet enters the running state when system calls start() method. It
occurs automatically after the applet in initialized.
- It can also occur if applet is already in idle state. Start() method may be called more than
once.
public void start() {------------------}
iii) Idle state:- An Applet become idle when it is stopped from running, stopping occurs
when we leave the page containing currently running applet.
- We can call stop() method explicitly.
public void stop() {------------------}
iv) Dead state:- An Applet is said to be dead when it is removed from memory. It occurs
automatically by invoking destroy() method.
- It can happen only once in applet‟s life cycle.
public void destroy() {------------------}
30
Written By: Sunil, Mahesh, Nitin
Internet Programming
v) Display state:- Applet moves to this state when it has to perform some output
operations on the screen. The paint() method is called to accomplish this task.
public void paint (Graphics g) {------------------}
<APPLET
[CODEBASE = codebaseVRL]
CODE = appletFile
[ALT = alternateText]
[NAME = appletInstanceName]
Width = pixels height = pixels
[ALIGN = alignments]
[VSPACE = pixels] [HSPACE = pixels]
>
[<PARAMNAME = AttributeName1 VALUE = AttributeValue1>]
[<PARAMNAME = AttributeName2 VALUE = AttributeValue2>]
...........
</APPLET>
Attributes are:
1) CODEBASE: It specifies base URL of applet code, which is the directory that will be
searched for applet‟s class.
2) CODE: It is required attribute that gives the name of the file containing applet‟s
compiled.class code.
31
Written By: Sunil, Mahesh, Nitin
Internet Programming
Program example:
import java.io.*;
import java.applet.*;
public class DemoParam extends Applet
{
String str;
public void init()
{
Str= getParamater(“String”);
if (str==null) str=”Java”;
str =”Hello” + str;
}
public void paint(Graphics g) {
g.drawString(str, 100,100);
}
}
HTML Code:
<APPLET CODE = “DemoParam.class”
WIDTH = 200 Height = 200>
<PARAM NAME = “String” value = “Applet”>
</APPLET>
{
mouseX=0, mouseY=10;
msg = “MouseEntered”;
repaint();
}
public void mousePressed(MouseEvent me)
{
mouseX=me.getX();
mouseY= me.getY();
msg = “Down”;
repaint();
}
public void mouseRealeased(MouseEvent me)
{
mouseX=me.getX();
mouseY= me.getY();
msg = “Up”;
repaint();
}
public void mouseDreagged((MouseEvent me)
{
mouseX=me.getX();
mouseY= me.getY();
msg = “*”;
showStatus(“dragging mouse at “+mouseX+” , “+mousey);
repaint();
}
public void mouseMoved(MouseEvent me)
{
Showstatus(“Mousing mouse at “+me.getX()+”, “me.getY());
}
}
}
public void paint(Graphics g) {
g.drawString(msg, X,y);
}
public void KeyPressed(KeyEvent ke)
{
showStatus(“KeyDown”);
}
public void KeyReleased(KeyEvent ke)
{
showStatus(“KeyUp”);
}
public void KeyTyped(KeyEvent ke)
{
msg +=ke.getKeyChar();
repaint();
}
}
34
Written By: Sunil, Mahesh, Nitin
Internet Programming
Chapter-9
Stream Classes
Types:
1) Input Streams: An input Streams extracts or reads the input data from the source and
sends it to program.
Two types:
a) Byte stream Classes: Input stream classes that are used 8-bits bytes. though there are
many classes related to byte streams but most frequently used classes are FileInputStream
and FileOutputStream.
b) Input stream classes: input stream classes are the base class of all input streams in the
java IO API. InputStream subclasses include the FileInputStream, BufferedInputStreams.
Methods Description
1) int read() - Reads the single byte data from the stream.
2) int read(byte[]) - Reads data into an array of bytes. it is determined by length
of byte array passed.
3) long skip(long) - Jumps over the specified number of bytes in streams.
4) int available() - Returns the number of bytes that can be read without
blocking.
}
catch(exception e)
{
System.out.println(e);
}
}
36
Written By: Sunil, Mahesh, Nitin
Internet Programming
Chapter – 10
Classes, Arrays, Strings and Vectors
i) Return type of methods can be same, but argument list of overloaded methods must
differ in number or in data type.
ii) Argument list of calling statement must differ enough to allow unambiguous
determination of proper method to call.
Overloading Overriding
1) Same method names but different 1) Same method names with same
arguments may or may not be same return arguments and same return types associated
type written in the same class itself. in class & its subclass.
2) Method name same but signature is 2) To re-define the basic class method in
different in the class. the derived class is called overriding.
38
Written By: Sunil, Mahesh, Nitin
Internet Programming
Chapter-11
Inheritance
- To declare the abstract class, we use keyword „abstract‟ before the class keyword in class
declaration:
41
Written By: Sunil, Mahesh, Nitin
Internet Programming
Chapter-12
Arrays, Strings and Vectors
Creating an Array: like any other variables, arrays must be declared and created in
computer memory before they are used.
3 steps involved:
i) Declaration
ii) Allocation
iii) Initialization
i) Declaration:- Like other variable in java, an array must have a specific type like byte,
int, string or double. only variables of appropriate type can be stored in an array.
int[] k;
float [] t;
String[] names;
ii) Creation of Arrays: When we create an array we need to tell the compiler how many
elements will be stored in it?
k= new int[2];
t= new float[5];
names = new String[50];
- We create an array with operator „new‟. It is reserved word in java that is used to allocate
not just an array.
iii) Initialization: Array can be initialized when they are declared. An array initialize is a
list of comma-separated expressions.
- The array will automatically create large enough to hold number of elements.
- Individual elements of array are referenced by the array name and by an integer which
represents their position in the array.
class Array
{
public static void main(String args[])
{
int month_days[] = {31,28,31,30,31,31,30,31,31};
42
Written By: Sunil, Mahesh, Nitin
Internet Programming
}
System.out.println(“April has “ + month_days[3]= “days.”);
}
}
43
Written By: Sunil, Mahesh, Nitin
Internet Programming
Chapter-13
Strings
Constructors Purpose
1) Strings() - Creates empty string.
2) String(String) - Creates string from specified string.
3) String(char[]) - Creates string from an array of character.
4) String(char[],int, int) - Creates string from specified subset of
character in array.
5) String(byte[],int) - Creates string from specified byte array.
6) String(StringBuffer) - Creates string.
Method Purpose
1) concat(String) - Concatenate one string into another.
2) compareTo(String) - Compare two strings. returns 0 if they are
equal.
6) copyString() - Copies one string into another.
44
Written By: Sunil, Mahesh, Nitin
Internet Programming
StringBuffer Constructors:
i) StringBuffer()
ii) StringBuffer(int size)
iii) StringBuffer(String str)
iv) StringBuffer(CharSequence char)
45
Written By: Sunil, Mahesh, Nitin
Internet Programming
Methods Purpose
1) Capacity() i) Returns current capacity of StringBuffer
2) charAt(int) ii) Returns character located at index.
3) ensureCapacity() iii) Ensures the capacity of StringBuffer at
least specified amount array.
Chapter-14
Vectors
Creating Vectors:
a) Create a Vector with default initial size
Vector v = new Vector();
b) Create a Vector with an initial size
Vector v = new Vector(300); // to add elements to end of vectors
Chapter-15
Wrapper Class
1) Write a note on Wrapper Class.
Ans: Wrapper class is wrapper around a primitive data type. It represents data types in
their corresponding class instances.
- All primitive wrapper class in Java are immutable. i.e once assigned a value to wrapper
class instance cannot be changed.
46
Written By: Sunil, Mahesh, Nitin