Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
6 views

java notes (1)

Java

Uploaded by

associatesk44
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

java notes (1)

Java

Uploaded by

associatesk44
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 60

Most of the contents are from http://www.javatpoint.

com ,
https://www.tutorialspoint.com
Java Version History
Java language developed by company Sun Microsystems and the creator
is Jamesh Gosling.
Some of the versions of java are
JDK Alpha and Beta (1995)
 JDK 1.0 (23rd Jan, 1996)
 JDK 1.1 (19th Feb, 1997)
 J2SE 1.2 (8th Dec, 1998)
 J2SE 1.3 (8th May, 2000)
 J2SE 1.4 (6th Feb, 2002)
 J2SE 5.0 (30th Sep, 2004)
 Java SE 6 (11th Dec, 2006)
 Java SE 7 (28th July, 2011)
 Java SE 8 (18th March, 2014)
Overview of Java
Java is one of the programming language or technology used for developing
web applications. Java language developed at SUN Micro Systems in the year
1995 under the guidance of James Gosling and there team. Originally SUN
Micro Systems is one of the Academic university (Standford University
Network)
Whatever the software developed in the year 1990, SUN Micro Systems has
released on the name of oak, which is original name of java (scientifically oak
is one of the tree name). The OAK has taken 18 months to develop.
The oak is unable to fulfill all requirements of the industry. So James Gosling
again reviews this oak and released with the name of java in the year 1995.
Scientifically java is one of the coffee seed name.
Java divided into three categories, they are
 J2SE (Java 2 Standard Edition)
 J2EE (Java 2 Enterprise Edition)
 J2ME (Java 2 Micro or Mobile Edition)
J2SE
J2SE is used for developing client side applications.
J2EE
J2EE is used for developing server side applications.
J2ME
J2ME is used for developing mobile or wireless application by making use of a
predefined protocol called WAP(wireless Access / Application protocol).
Features of Java
There is given many features of java. They are also known as java
buzzwords. The Java Features given below are simple and easy to
understand.
1.Simple
2.Object-Oriented
3.Platform independent
4.Secured
5.Robust
6.Architecture neutral
7.Portable
8.Dynamic
9.Interpreted
10. High Performance
11. Multithreaded
12. Distributed
Simple
According to Sun, Java language is simple because:
syntax is based on C++ (so easier for programmers to learn it
after C++).
removed many confusing and/or rarely-used features e.g.,
explicit pointers, operator overloading etc.
No need to remove unreferenced objects because there is
Automatic Garbage Collection in java.

Object-oriented
Object-oriented means we organize our software as a combination
of different types of objects that incorporates both data and
behaviour.
Object-oriented programming(OOPs) is a methodology that simplify
software development and maintenance by providing some rules.
Basic concepts of OOPs are:
1. Object
2. Class
3. Inheritance
4. Polymorphism
5. Abstraction
6. Encapsulation
Platform Independent

A platform is the hardware or software environment in which a


program runs.
There are two types of platforms software-based and hardware-based.
Java provides software-based platform.
The Java platform differs from most other platforms in the sense that
it is a software-based platform that runs on the top of other
hardware-based platforms. It has two components:
1. Runtime Environment
2. API(Application Programming Interface)
Java code can be run on multiple platforms e.g. Windows, Linux, Sun
Solaris, Mac/OS etc. Java code is compiled by the compiler and
converted into bytecode. This bytecode is a platform-independent
code because it can be run on multiple platforms i.e. Write Once and
Run Anywhere(WORA).

Secured
Java is secured because:
o No explicit pointer
o Java Programs run inside virtual machine sandbox

o Classloader: adds security by separating the package for the


classes of the local file system from those that are imported from
network sources.
o Bytecode Verifier: checks the code fragments for illegal code
that can violate access right to objects.
o Security Manager: determines what resources a class can
access such as reading and writing to the local disk.
These security are provided by java language. Some security can also
be provided by application developer through SSL, JAAS,
Cryptography etc.

Robust
Robust simply means strong. Java uses strong memory management.
There are lack of pointers that avoids security problem. There is
automatic garbage collection in java. There is exception handling and
type checking mechanism in java. All these points makes java robust.

Architecture-neutral
There is no implementation dependent features e.g. size of primitive
types is fixed.
In C programming, int data type occupies 2 bytes of memory for 32-
bit architecture and 4 bytes of memory for 64-bit architecture. But in
java, it occupies 4 bytes of memory for both 32 and 64 bit
architectures.

Portable
We may carry the java bytecode to any platform.

High-performance
Java is faster than traditional interpretation since byte code is
"close" to native code still somewhat slower than a compiled
language (e.g., C++)

Distributed
We can create distributed applications in java. RMI and EJB are used
for creating distributed applications. We may access files by calling
the methods from any machine on the internet.

Multi-threaded
A thread is like a separate program, executing concurrently. We can
write Java programs that deal with many tasks at once by defining
multiple threads. The main advantage of multi-threading is that it
doesn't occupy memory for each thread. It shares a common memory
area. Threads are important for multi-media, Web applications etc.
Java is Robust because it is highly supported language. It is portable across
many Operating systems. Java also has feature of Automatic memory
management and garbage collection. Strong type checking mechanism
of Java also helps in makingJava Robust. Bugs, especially system crashing
bugs, are very rare in Java.
Java is considered as Portable because – Output of a Java compiler is Non
Executable Code i.e Bytecode. Bytecode is executed by Java run-time system,
which is called the Java Virtual Machine (JVM).
Java is considered as Dynamic because of Bytecode[a class file]. A source
code writen in one platform, the same code can be executed in any platform[
which JDK is installed.]. And it also loads the class files at runtime. anything that
happes at runtime is considered as Dynamic, so the java is.
To enable a Java application to execute anywhere on the network, the compiler
generates an architecture-neutral object file format--the compiled code is
executable on many processors, given the presence of the Java runtime
system. This is useful not only for networks but also for single system software
distribution.
C++ vs Java
There are many differences and similarities between C++
programming language and Java. A list of top differences between
C++ and Java are given below:
Comparison Index C++ Java
Platform- C++ is platform- Java is platform-independent.
independent dependent.
Mainly used C++ is mainly used for Java is mainly used for
for system programming. application programming. It is
widely used in window, web-
based, enterprise and mobile
applications.
Goto C++ supports goto Java doesn't support goto
statement. statement.
Multiple C++ supports multiple Java doesn't support multiple
inheritance inheritance. inheritance through class. It
can be achieved by interfaces
in java.
Operator C++ supports operator Java doesn't support operator
Overloading overloading. overloading.
Pointers C++ supports Java supports pointer
pointers. You can write internally. But you can't write
pointer program in the pointer program in java. It
C++. means java has restricted
pointer support in java.
Compiler and C++ uses compiler Java uses compiler and
Interpreter only. interpreter both.
Call by Value C++ supports both call Java supports call by value
and Call by by value and call by only. There is no call by
reference reference. reference in java.
Structure and C++ supports Java doesn't support structures
Union structures and unions. and unions.
Thread C++ doesn't have Java has built-in thread
Support built-in support for support.
threads. It relies on
third-party libraries for
thread support.
Documentation C++ doesn't support Java supports documentation
comment documentation comment (/** ... */) to create
comment. documentation for java source
code.
Virtual C++ supports virtual Java has no virtual keyword.
Keyword keyword so that we We can override all non-static
can decide whether or methods by default. In other
not override a words, non-static methods are
function. virtual by default.
unsigned right C++ doesn't support Java supports unsigned right
shift >>> >>> operator. shift >>> operator that fills
zero at the top for the negative
numbers. For positive
numbers, it works same like
>> operator.
Inheritance C++ creates a new Java uses single inheritance
Tree inheritance tree tree always because all classes
always. are the child of Object class in
java. Object class is the root of
inheritance tree in java.

What is JVM?
Java Virtual Machine (JVM) is a engine that provides runtime environment to
drive the Java Code or applications. It converts Java bytecode into machines
language. JVM is a part of Java Runtime Environment (JRE). In other
programming languages, the compiler produces machine code for a particular
system. However, Java compiler produces code for a Virtual Machine known as
Java Virtual Machine.
How JVM Works?
First, Java code is compiled into bytecode. This bytecode gets interpreted on
different machines
Between host system and Java source, Bytecode is an intermediary language.
JVM in Java is responsible for allocating memory space.

Working of Java Virtual Machine (JVM)


JVM Architecture
Now in this JVM tutorial, let’s understand the Architecture of JVM. JVM
architecture in Java contains classloader, memory area, execution engine etc.
Java
Virtual Machine Architecture

1) ClassLoader
The class loader is a subsystem used for loading class files. It performs three
major functions viz. Loading, Linking, and Initialization.
2) Method Area
JVM Method Area stores class structures like metadata, the constant runtime
pool, and the code for methods.
3) Heap
All the Objects, their related instance variables, and arrays are stored in the
heap. This memory is common and shared across multiple threads.
4) JVM language Stacks
Java language Stacks store local variables, and it’s partial results. Each thread
has its own JVM stack, created simultaneously as the thread is created. A new
frame is created whenever a method is invoked, and it is deleted when method
invocation process is complete.
5) PC Registers
PC register store the address of the Java virtual machine instruction which is
currently executing. In Java, each thread has its separate PC register.
6) Native Method Stacks
Native method stacks hold the instruction of native code depends on the native
library. It is written in another language instead of Java.
7) Execution Engine
It is a type of software used to test hardware, software, or complete systems.
The test execution engine never carries any information about the tested
product.
8) Native Method interface
The Native Method Interface is a programming framework. It allows Java code
which is running in a JVM to call by libraries and native applications.
9) Native Method Libraries
Native Libraries is a collection of the Native Libraries(C, C++) which are needed
by the Execution Engine.
Software Code Compilation & Execution process
In order to write and execute a software program, you need the following
1) Editor – To type your program into, a notepad could be used for this
2) Compiler – To convert your high language program into native machine code
3) Linker – To combine different program files reference in your main program
together.
4) Loader – To load the files from your secondary storage device like Hard Disk,
Flash Drive, CD into RAM for execution. The loading is automatically done when
you execute your code.
5) Execution – Actual execution of the code which is handled by your OS &
processor.
With this background, refer the following video & learn the JVM internal working
and architecture of JVM (Java Virtual Machine).
What is Java Bytecode?
Java bytecode is the instruction set for the Java Virtual Machine. It acts similar to
an assembler which is an alias representation of a C++ code. As soon as a java
program is compiled, java bytecode is generated. In more apt terms, java
bytecode is the machine code in the form of a .class file. With the help of java
bytecode we achieve platform independence in java.
How does it works?
When we write a program in Java, firstly, the compiler compiles that program
and a bytecode is generated for that piece of code. When we wish to run this
.class file on any other platform, we can do so. After the first compilation, the
bytecode generated is now run by the Java Virtual Machine and not the
processor in consideration. This essentially means that we only need to have
basic java installation on any platforms that we want to run our code on.
Resources required to run the bytecode are made available by theJava Virtual
Machine, which calls the processor to allocate the required resources. JVM's are
stack-based so they stack implementation to read the codes.

Advantage of Java Bytecode


Platform independence is one of the soul reasons for which James Gosling
started the formation of java and it is this implementation of bytecode which
helps us to achieve this. Hence bytecode is a very important component of any
java program.The set of instructions for the JVM may differ from system to
system but all can interpret the bytecode. A point to keep in mind is that
bytecodes are non-runnable codes and rely on the availability of an interpreter
to execute and thus the JVM comes into play.
Bytecode is essentially the machine level language which runs on the Java Virtual
Machine. Whenever a class is loaded, it gets a stream of bytecode per method of
the class. Whenever that method is called during the execution of a program, the
bytecode for that method gets invoked.Javac not only compiles the program but
also generates the bytecode for the program. Thus, we have realized that the
bytecode implementation makes Java a platform-independent language. This
helps to add portability to Java which is lacking in languages like C or C++.
Portability ensures that Java can be implemented on a wide array of platforms
like desktops, mobile devices, severs and many more. Supporting this, Sun
Microsystems captioned JAVA as "write once, read anywhere" or "WORA" in
resonance to the bytecode interpretation.

Garbage Collection in Java

Garbage collection in Java is the process by which Java programs perform automatic
memory management. Java programs compile to bytecode that can be run on a Java
Virtual Machine, or JVM for short. When Java programs run on the JVM, objects are
created on the heap, which is a portion of memory dedicated to the program.
Eventually, some objects will no longer be needed. The garbage collector finds these
unused objects and deletes them to free up memory.
What is Garbage Collection?
In C/C++, a programmer is responsible for both the creation and destruction of objects.
Usually, programmer neglects the destruction of useless objects. Due to this
negligence, at a certain point, sufficient memory may not be available to create new
objects, and the entire program will terminate abnormally, causing
OutOfMemoryErrors.
But in Java, the programmer need not care for all those objects which are no longer in
use. Garbage collector destroys these objects. The main objective of Garbage Collector
is to free heap memory by destroying unreachable objects. The garbage collector is the
best example of the Daemon thread as it is always running in the background.
How Does Garbage Collection in Java works?
Java garbage collection is an automatic process. Automatic garbage collection is the
process of looking at heap memory, identifying which objects are in use and which are
not, and deleting the unused objects. An in-use object, or a referenced object, means
that some part of your program still maintains a pointer to that object. An unused or
unreferenced object is no longer referenced by any part of your program. So the
memory used by an unreferenced object can be reclaimed. The programmer does not
need to mark objects to be deleted explicitly. The garbage collection implementation
lives in the JVM.
Variables and Data Types
Programs are often required to store information. For example, to write a
program that adds two numbers, we need to store the first number, the second
number and the result. This is accomplished by the use of variables. Variables
represent memory area where the information is stored. Following is the
physical representation of a variable:

A variable has a name, a value and a data type. A variable name is a symbolic
representation of the memory area in which the information would be stored.
The value is the actual data that is going to be stored. And a particular variable
can only store one type of information. It could either be an integer, a real
number, a single character or a String. This is specified by the data type.

In our example, we have a variable named firstNumber of type int and having a
value 3. The data
Range ( in
Data Range (inclusive of both
Size in bits exponential
type values)
notation)
byte 8 - 128 to 127 - 27 to 27-1
short 16 - 32 768 to 32 767 - 215 to 215 -1
- 2 147 483 648 to 2 147 483
int 32 - 231 to 231 -1
647
- 9 223 372 036 854 775 808
long 64 - 263 to 263 -1
to 9 223 372 036 854 775 807
float 32 -3.4*10-38 to 3.4*1038
-1.7*10-308 to
double 64
1.7*10308
char 16 0 to 65536
Not properly
boolean true and false
defined
naming conventions in java
By using standard Java naming conventions, you make your code
easier to read for yourself and for other programmers. Readability of
Java program is very important. It indicates that less time is spent to
figure out what the code does.
Name Convention
class should start with uppercase letter and be a noun e.g.
name String, Color, Button, System, Thread etc.
interface should start with uppercase letter and be an adjective e.g.
name Runnable, Remote, ActionListener etc.
method should start with lowercase letter and be a verb e.g.
name actionPerformed(), main(), print(), println() etc.
variable should start with lowercase letter e.g. firstName,
name orderNumber etc.
package should be in lowercase letter e.g. java, lang, sql, util etc.
name
constants should be in uppercase letter. e.g. RED, YELLOW,
name MAX_PRIORITY etc.

Java - Basic Operators

Java provides a rich set of operators to manipulate variables. We can


divide all the Java operators into the following groups −
 Arithmetic Operators
 Relational Operators
 Bitwise Operators
 Logical Operators
 Assignment Operators
 Misc Operators
The Arithmetic Operators
Arithmetic operators are used in mathematical expressions in the
same way that they are used in algebra. The following table lists the
arithmetic operators −
Assume integer variable A holds 10 and variable B holds 20, then −
Show Examples
Operator Description Example

Adds values on either side of A+B


+ (Addition) the operator. will give
30

Subtracts right-hand operand A - B will


- (Subtraction)
from left-hand operand. give -10

* Multiplies values on either side A * B will


(Multiplication) of the operator. give 200

Divides left-hand operand by B / A will


/ (Division)
right-hand operand. give 2

Divides left-hand operand by B%A


% (Modulus) right-hand operand and will give
returns remainder. 0

++ Increases the value of operand B++


(Increment) by 1. gives 21

Decreases the value of B-- gives


-- (Decrement)
operand by 1. 19
The Relational Operators
There are following relational operators supported by Java language.
Assume variable A holds 10 and variable B holds 20, then −
Show Examples
Operator Description Example

== (equal Checks if the values of two (A == B)


to) operands are equal or not, if is not true.
yes then condition becomes
true.

Checks if the values of two


!= (not operands are equal or not, if (A != B) is
equal to) values are not equal then true.
condition becomes true.

Checks if the value of left


> (greater operand is greater than the (A > B) is
than) value of right operand, if yes not true.
then condition becomes true.

Checks if the value of left


operand is less than the value (A < B) is
< (less than)
of right operand, if yes then true.
condition becomes true.

Checks if the value of left


>= (greater operand is greater than or
(A >= B)
than or equal to the value of right
is not true.
equal to) operand, if yes then condition
becomes true.

Checks if the value of left


<= (less operand is less than or equal
(A <= B)
than or to the value of right operand, if
is true.
equal to) yes then condition becomes
true.
The Bitwise Operators
Java defines several bitwise operators, which can be applied to the
integer types, long, int, short, char, and byte.
Bitwise operator works on bits and performs bit-by-bit operation.
Assume if a = 60 and b = 13; now in binary format they will be as
follows −
a = 0011 1100
b = 0000 1101
-----------------
a&b = 0000 1100
a|b = 0011 1101
a^b = 0011 0001
~a = 1100 0011
The following table lists the bitwise operators −
Assume integer variable A holds 60 and variable B holds 13 then −
Show Examples
Operator Description Example

Binary AND Operator


(A & B) will give
& (bitwise copies a bit to the
12 which is 0000
and) result if it exists in both
1100
operands.

Binary OR Operator (A | B) will give


| (bitwise or) copies a bit if it exists 61 which is 0011
in either operand. 1101

Binary XOR Operator


(A ^ B) will give
^ (bitwise copies the bit if it is set
49 which is 0011
XOR) in one operand but not
0001
both.

(~A ) will give -61


Binary Ones which is 1100
~ (bitwise Complement Operator 0011 in 2's
compliment) is unary and has the complement form
effect of 'flipping' bits. due to a signed
binary number.

Binary Left Shift


Operator. The left
A << 2 will give
<< (left operands value is
240 which is 1111
shift) moved left by the
0000
number of bits specified
by the right operand.

>> (right Binary Right Shift A >> 2 will give


shift) Operator. The left 15 which is 1111
operands value is
moved right by the
number of bits specified
by the right operand.

Shift right zero fill


operator. The left
operands value is
>>> (zero A >>>2 will give
moved right by the
fill right 15 which is 0000
number of bits specified
shift) 1111
by the right operand
and shifted values are
filled up with zeros.
The Logical Operators
The following table lists the logical operators −
Assume Boolean variables A holds true and variable B holds false,
then −
Show Examples
Operator Description Example

Called Logical AND


operator. If both the
&& (logical and) operands are non-zero, (A && B) is false
then the condition
becomes true.

Called Logical OR
Operator. If any of the
two operands are non-
|| (logical or) (A || B) is true
zero, then the
condition becomes
true.

Called Logical NOT


Operator. Use to
! (logical not) !(A && B) is true
reverses the logical
state of its operand. If
a condition is true then
Logical NOT operator
will make false.
The Assignment Operators
Following are the assignment operators supported by Java language

Show Examples
Operator Description Example

Simple assignment operator. C=A+B


Assigns values from right side will assign
=
operands to left side operand. value of A
+ B into C

Add AND assignment operator. It C += A is


adds right operand to the left equivalent
+=
operand and assign the result to to C = C
left operand. +A

Subtract AND assignment operator. C -= A is


It subtracts right operand from the equivalent
-=
left operand and assign the result to C = C
to left operand. –A

Multiply AND assignment operator. C *= A is


It multiplies right operand with the equivalent
*=
left operand and assign the result to C = C
to left operand. *A

Divide AND assignment operator. It C /= A is


divides left operand with the right equivalent
/=
operand and assign the result to to C = C /
left operand. A

Modulus AND assignment operator. C %= A is


It takes modulus using two equivalent
%=
operands and assign the result to to C = C
left operand. %A
C <<= 2
is same
<<= Left shift AND assignment operator.
as C = C
<< 2

C >>= 2
is same
>>= Bitwise AND assignment operator.
as C = C
>> 2

C &= 2 is
Right shift AND assignment
&= same as C
operator.
=C&2

bitwise exclusive OR and C ^= 2 is


^= assignment operator. same as C
=C^2

bitwise inclusive OR and C |= 2 is


|= assignment operator. same as C
=C|2
Miscellaneous Operators
There are few other operators supported by Java Language.
Conditional Operator ( ? : )
Conditional operator is also known as the ternary operator. This
operator consists of three operands and is used to evaluate Boolean
expressions. The goal of the operator is to decide, which value should
be assigned to the variable. The operator is written as −
variable x = (expression) ? value if true : value if false
Following is an example −
Example
public class Test {
public static void main(String args[]) {
int a, b;
a = 10;
b = (a == 1) ? 20: 30;
System.out.println( "Value of b is : " + b );
b = (a == 10) ? 20: 30;
System.out.println( "Value of b is : " + b );
}
}
This will produce the following result −
Output
Value of b is : 30
Value of b is : 20
instanceof Operator
This operator is used only for object reference variables. The operator
checks whether the object is of a particular type (class type or
interface type). instanceof operator is written as −
( Object reference variable ) instanceof (class/interface type)
If the object referred by the variable on the left side of the operator
passes the IS-A check for the class/interface type on the right side,
then the result will be true. Following is an example −
Example
public class Test {
public static void main(String args[]) {
String name = "James";
// following will return true since name is type of String
boolean result = name instanceof String;
System.out.println( result );
}
}
This will produce the following result −
Output
true
This operator will still return true, if the object being compared is the
assignment compatible with the type on the right. Following is one
more example −
Example
class Vehicle {}
public class Car extends Vehicle {
public static void main(String args[]) {
Vehicle a = new Car();
boolean result = a instanceof Car;
System.out.println( result );
}
}
This will produce the following result −
Output
true
Precedence of Java Operators
Operator precedence determines the grouping of terms in an
expression. This affects how an expression is evaluated. Certain
operators have higher precedence than others; for example, the
multiplication operator has higher precedence than the addition
operator −
For example, x = 7 + 3 * 2; here x is assigned 13, not 20 because
operator * has higher precedence than +, so it first gets multiplied
with 3 * 2 and then adds into 7.
Here, operators with the highest precedence appear at the top of the
table, those with the lowest appear at the bottom. Within an
expression, higher precedence operators will be evaluated first.
Category Operator Associativity

Postfix >() [] . (dot operator) Left toright

Unary >++ - - ! ~ Right to left

Multiplicative >* / Left to right

Additive >+ - Left to right

Shift >>> >>> << Left to right

Relational >> >= < <= Left to right

Equality >== != Left to right

Bitwise AND >& Left to right

Bitwise XOR >^ Left to right


Bitwise OR >| Left to right

Logical AND >&& Left to right

Logical OR >|| Left to right

Conditional ?: Right to left

Assignment >= += -= *= /= %= >>= Right to left


<<= &= ^= |=

Array In Java
An array is used to store a group of values, all of which have the same data
type. All the elements stored in the arrays are accessed by simply using the
variable name and the index of the element
The following statements show the declaration of an array named a, which holds
int values.
int [] a;
The square brackets may also be placed at the end of the array name, as shown
below. It would make no difference.
int a[];
Just like variables, we may also declare more than one array in a single
statement, as shown below:
int[] a, b, c;
The new keyword returns a reference to the array being created which is then
assigned to an appropriate variable. The size of the arrays (or the length, which
is the number of elements the array will hold) is also specified. Following
statements creates an array to hold seven integers and assigns its reference to
eth arrays variable a.
a = new int[7];
As with variables, the declaration and initialisation of arrays can be combined
into s ingle statement as shown below:
int[] a = new int[7];
The following statements initialise some of the elements of the array a.
a[0]=3;
a[1]=34;
a[5]=7;
Elements accessed with the above notation ( a[index] ) may be used just like
normal variables. We may print those values, use them in calculations, pass
them as arguments and so on.
System.out.println( a[1] );
int sum = a[6] + a[5];
double root = Math.sqrt ( a[5] );
Processing Arrays using Loops
It would be quite difficult to process each of the array's elements individually as
we have done in the previous chapter. Since these are repetitive tasks,
repetition statements like for and while come to our rescue. The common
approach is to use a for loop with a variable used to keep track of the index
number and iterate through the entire array.
For example, the following code stores the numbers from 1 to 7 in a seven
element int array.
int[] a =new int[7];
for ( int i=0; i<a.length; i++) {
a[i]= i+1;
}
In a similar way, a for loop can be used to print the elements of the array.
for ( int i=0; i<a.length; i++) {
System.out.println("Element at index "+i+" is "+a[i]);
}
And the code below stores the first seven even numbers in the array a, starting
from 2.
for ( int i=0; i<a.length; i++) {
a[i] = (i+1) * 2;
}
Simple Example of for-each loop for traversing the array elements:
1.
2. class ForEachExample1{
3. public static void main(String args[]){
4. int arr[]={12,13,14,44};
5.
6. for(int i:arr){
7. System.out.println(i);
8. }
9.
10. }
11. }
Control Statement in Java
In Java, control statements can be divided into the following three categories:
 Selection Statements
 Iteration Statements
 Jump Statements
Selection Statements

Selection statements allow you to control the flow of program execution on the
basis of the outcome of an expression or state of a variable known during
runtime.

Selection statements can be divided into the following categories:


 The if and if-else statements
 The if-else statements
 The if-else-if statements
 The switch statements
The if statements

The first contained statement (that can be a block) of an if statement only


executes when the specified condition is true. If the condition is false and there
is not else keyword then the first contained statement will be skipped and
execution continues with the rest of the program. The condition is an expression
that returns a boolean value.

Example
1.
2. import java.util.Scanner;
3.
4. public class IfDemo
5. {
6. public static void main(String[] args) {
7.
8. int age;
9. Scanner inputDevice = new Scanner(System.in);
10. System.out.print("Please enter Age: ");
11. age = inputDevice.nextInt();
12. if(age > 18)
13. System.out.println("above 18 ");
14. }
15.
16. }
Output:

The if-else statements

In if-else statements, if the specified condition in the if statement is false, then


the statemet after the else keyword (that can be a block) will execute.

Example
1.
2. import java.util.Scanner;
3.
4. public class IfElseDemo
5. {
6. public static void main( String[] args )
7. {
8. int age;
9. Scanner inputDevice = new Scanner( System.in );
10. System.out.print( "Please enter Age: " );
11. age = inputDevice.nextInt();
12. if ( age >= 18 )
13. System.out.println( "above 18 " );
14. else
15. System.out.println( "below 18" );
16. }
17. }
Output

The if-else-if statements

This statement following the else keyword can be another if or if-else statement.
That would looks like this:

if(condition)
statements;
else if (condition)
statements;
else if(condition)
statement;
else
statements;

Whenever the condition is true, the associated statement will be executed and
the remaining conditions will be bypassed. If none of the conditions are true then
the else block will execute.

Example
1.
2. import java.util.Scanner;
3.
4. public class IfElseIfDemo
5. {
6. public static void main( String[] args )
7. {
8. int age;
9. Scanner inputDevice = new Scanner( System.in );
10. System.out.print( "Please enter Age: " );
11. age = inputDevice.nextInt();
12. if ( age >= 18 && age <=35 )
13. System.out.println( "between 18-35 " );
14. else if(age >35 && age <=60)
15. System.out.println("between 36-60");
16. else
17. System.out.println( "not matched" );
18. }
19. }
Output
The Switch Statements

The switch statement is a multi-way branch statement. The switch statement of


Java is another selection statement that defines multiple paths of execution of a
program. It provides a better alternative than a large series of if-else-if
statements.

Example
1.
2. import java.util.Scanner;
3.
4. public class SwitchDemo
5. {
6. public static void main( String[] args )
7. {
8. int age;
9. Scanner inputDevice = new Scanner( System.in );
10. System.out.print( "Please enter Age: " );
11. age = inputDevice.nextInt();
12. switch ( age )
13. {
14. case 18:
15. System.out.println( "age 18" );
16. break;
17. case 19:
18. System.out.println( "age 19" );
19. break;
20. default:
21. System.out.println( "not matched" );
22. break;
23. }
24. }
25. }
Output

An expression must be of a type of byte, short, int or char. Each of the values
specified in the case statement must be of a type compatible with the
expression. Duplicate case values are not allowed. The break statement is used
inside the switch to terminate a statement sequence. The break statement is
optional in the switch statement.

Iteration Statements

Repeating the same code fragment several times until a specified condition is
satisfied is called iteration. Iteration statements execute the same set of
instructions until a termination condition is met.

Java provides the following loop for iteration statements:


 The while loop
 The for loop
 The do-while loop
 The for each loop
The while loop

It continually executes a statement (that is usually be a block) while a condition


is true. The condition must return a boolean value.

Example
1.
2. public class WhileDemo
3. {
4. public static void main( String[] args )
5. {
6. int i = 0;
7. while ( i < 5 )
8. {
9. System.out.println( "Value :: " + i );
10. i++;
11. }
12. }
13. }
Output

The do-while loop


The only difference between a while and a do-while loop is that do-while
evaluates its expression at the bottom of the loop instead of the top. The do-
while loop executes at least one time then it will check the expression prior to
the next iteration.

Example
1.
2. public class DoWhileDemo
3. {
4. public static void main( String[] args )
5. {
6. int i = 0;
7. do
8. {
9. System.out.println( "value :: " + i );
10. i++;
11. }
12. while ( i < 5);
13. }
14. }
Output

The for loop

A for loop executes a statement (that is usually a block) as long as the boolean
condition evaluates to true. A for loop is a combination of the three elements
initialization statement, boolean expression and increment or decrement
statement.

Syntax:

for(<initialization>;<condition>;<increment or decrement statement>){


<block of code>
}

The initialization block executes first before the loop starts. It is used to initialize
the loop variable.

The condition statement evaluates every time prior to when the statement (that
is usually be a block) executes, if the condition is true then only the statement
(that is usually a block) will execute.

The increment or decrement statement executes every time after the statement
(that is usually a block).

Example
1.
2. public class WhileDemo
3. {
4. public static void main( String[] args )
5. {
6. int i = 0;
7. while ( i < 5 )
8. {
9. System.out.println( "Value :: " + i );
10. i++;
11. }
12. }
13. }
Output

The For each loop

This was introduced in Java 5. This loop is basically used to traverse the array
or collection elements.

Example
1.
2. public class ForEachDemo
3. {
4. public static void main( String[] args )
5. {
6. int[] i =
7. { 1, 2, 3, 4, 5 };
8. for ( int j : i )
9. {
10. System.out.println( "value :: " + j );
11. }
12. }
13. }
Output

Jump Statements

Jump statements are used to unconditionally transfer the program control to


another part of the program.
Java provides the following jump statements:
 break statement
 continue statement
 return statement
Break Statement

The break statement immediately quits the current iteration and goes to the first
statement following the loop. Another form of break is used in the switch
statement.

The break statement has the following two forms:


 Labeled Break Statement
 Unlabeled Break Statement
Unlabeled Break Statement: This is used to jump program control out of the
specific loop on the specific condition.

Example
1.
2. public class UnLabeledBreakDemo
3. {
4. public static void main( String[] args )
5. {
6. for ( int var = 0; var < 5; var++ )
7. {
8. System.out.println( "Var is : " + var );
9. if ( var == 3 )
10. break;
11. }
12. }
13. }
Output

Labeled Break Statement: This is used for when we want to jump the program
control out of nested loops or multiple loops.

Example
1.
2. public class LabeledBreakDemo
3. {
4. public static void main( String[] args )
5. {
6. Outer: for ( int var1 = 0; var1 < 5; var1++ )
7. {
8. for ( int var2 = 1; var2 < 5; var2++ )
9. {
10. System.out.println( "var1:" + var1 + ",
var2:" + var2 );
11. if ( var1 == 3 )
12. break Outer;
13. }
14. }
15. }
16. }
Output

Continue Statement

The continue statement is used when you want to continue running the loop with
the next iteration and want to skip the rest of the statements of the body for the
current iteration.

The continue statement has the following two forms:


 Labeled Continue Statement
 Unlabeled Continue Statement
Unlabeled Continue Statement: This statement skips the current iteration of
the innermost for, while and do-while loop.

Example
1.
2. public class UnlabeledContinueDemo
3. {
4. public static void main( String[] args )
5. {
6. for ( int var1 = 0; var1 < 4; var1++ )
7. {
8. for ( int var2 = 0; var2 < 4; var2++ )
9. {
10. if ( var2 == 2 )
11. continue;
12. System.out.println( "var1:" + var1 + ",
var2:" + var2 );
13. }
14. }
15. }
16. }
Example

Labeled Continue Statement: This statement skips the current iteration of the
loop with the specified label.

Example
public class LabeledContinueDemo
{
public static void main( String[] args )
{
Outer: for ( int var1 = 0; var1 < 5; var1++ )
{
for ( int var2 = 0; var2 < 5; var2++ )
{
if ( var2 == 2 )
continue Outer;
System.out.println( "var1:" + var1 + ", var2:"
+ var2 );
}
}
}
}
Output

Return Statement

The return statement is used to immediately quit the current method and return
to the calling method. It is mandatory to use a return statement for non-void
methods to return a value.

Example
public class ReturnDemo
{
public static void main( String[] args )
{
ReturnDemo returnDemo = new ReturnDemo();
System.out.println( "No : " + returnDemo.returnCall()
);
}

int returnCall()
{
return 5;
}
}
Recursion in Java
Recursion in java is a process in which a method calls itself
continuously. A method in java that calls itself is called recursive
method.
Java Recursion Example 1: Infinite times
public class RecursionExample1 {
static void p(){
System.out.println("hello");
p();
}

public static void main(String[] args) {


p();
}
}
Output:
hello
hello
...
java.lang.StackOverflowError
Java Recursion Example 2: Finite times
public class RecursionExample2 {
static int count=0;
static void p(){
count++;
if(count<=5){
System.out.println("hello "+count);
p();
}
}
public static void main(String[] args) {
p();
}
}
Output:
hello 1
hello 2
hello 3
hello 4
hello 5
Wrapper class in Java
Wrapper class in java provides the mechanism to convert primitive
into object and object into primitive.
Since J2SE 5.0, autoboxing and unboxing feature converts primitive
into object and object into primitive automatically. The automatic
conversion of primitive into object is known as autoboxing and vice-
versa unboxing.
The eight classes of java.lang package are known as wrapper classes
in java. The list of eight wrapper classes are given below:
Primitive Type Wrapper class
boolean Boolean
char Character
byte Byte
short Short
int Integer
long Long
float Float
double Double

Java Scanner class


There are various ways to read input from the keyboard, the
java.util.Scanner class is one of them.
The Java Scanner class breaks the input into tokens using a
delimiter that is whitespace bydefault. It provides many methods to
read and parse various primitive values.
Java Scanner class is widely used to parse text for string and primitive
types using regular expression.
Java Scanner class extends Object class and implements Iterator and
Closeable interfaces.
Commonly used methods of Scanner class
There is a list of commonly used Scanner class methods:
Method Description
public String next() it returns the next token from the scanner.
public String it moves the scanner position to the next line and
nextLine() returns the value as a string.
public byte it scans the next token as a byte.
nextByte()
public short it scans the next token as a short value.
nextShort()
public int nextInt() it scans the next token as an int value.
public long it scans the next token as a long value.
nextLong()
public float it scans the next token as a float value.
nextFloat()
public double it scans the next token as a double value.
nextDouble()
import java.util.Scanner;
class ScannerTest{
public static void main(String args[]){
Scanner sc=new Scanner(System.in);

System.out.println("Enter your rollno");


int rollno=sc.nextInt();
System.out.println("Enter your name");
String name=sc.next();
System.out.println("Enter your fee");
double fee=sc.nextDouble();
System.out.println("Rollno:"+rollno+" name:"+name+" fee:"+fee);
sc.close();
}
}
Wrapper classes in Java
The wrapper class in Java provides the mechanism to convert
primitive into object and object into primitive.
Since J2SE 5.0, autoboxing and unboxing feature convert primitives
into objects and objects into primitives automatically. The automatic
conversion of primitive into an object is known as autoboxing and
vice-versa unboxing.
Use of Wrapper classes in Java
Java is an object-oriented programming language, so we need to deal
with objects many times like in Collections, Serialization,
Synchronization, etc. Let us see the different scenarios, where we
need to use the wrapper classes.
Change the value in Method: Java supports only call by value. So, if
we pass a primitive value, it will not change the original value. But, if
we convert the primitive value in an object, it will change the original
value.
Serialization: We need to convert the objects into streams to perform
the serialization. If we have a primitive value, we can convert it in
objects through the wrapper classes.
Synchronization: Java synchronization works with objects in
Multithreading.
java.util package: The java.util package provides the utility classes to
deal with objects.
Collection Framework: Java collection framework works with objects
only. All classes of the collection framework (ArrayList, LinkedList,
Vector, HashSet, LinkedHashSet, TreeSet, PriorityQueue, ArrayDeque,
etc.) deal with objects only.
The eight classes of the java.lang package are known as wrapper
classes in Java. The list of eight wrapper classes are given below:
Primitive Type Wrapper class
boolean Boolean
char Character
byte Byte
short Short
int Integer
long Long
float Float
double Double
Autoboxing
The automatic conversion of primitive data type into its corresponding
wrapper class is known as autoboxing, for example, byte to Byte, char
to Character, int to Integer, long to Long, float to Float, boolean to
Boolean, double to Double, and short to Short.
Since Java 5, we do not need to use the valueOf() method of wrapper
classes to convert the primitive into objects.
Wrapper class Example: Primitive to Wrapper
//Java program to convert primitive into objects
//Autoboxing example of int to Integer
public class WrapperExample1{
public static void main(String args[]){
//Converting int into Integer
int a=20;
Integer i=Integer.valueOf(a);//converting int into Integer explicitly
Integer j=a;//autoboxing, now compiler will write Integer.valueOf(a)
internally

System.out.println(a+" "+i+" "+j);


}}
Output:
freestar
20 20 20
Unboxing
The automatic conversion of wrapper type into its corresponding
primitive type is known as unboxing. It is the reverse process of
autoboxing. Since Java 5, we do not need to use the intValue()
method of wrapper classes to convert the wrapper type into
primitives.
Wrapper class Example: Wrapper to Primitive
//Java program to convert object into primitives
//Unboxing example of Integer to int
public class WrapperExample2{
public static void main(String args[]){
//Converting Integer to int
Integer a=new Integer(3);
int i=a.intValue();//converting Integer to int explicitly
int j=a;//unboxing, now compiler will write a.intValue() internally

System.out.println(a+" "+i+" "+j);


}}
Output:
333
Java Naming conventions
Java naming convention is a rule to follow as you decide what to
name your identifiers such as class, package, variable, constant,
method etc.
But, it is not forced to follow. So, it is known as convention not rule.
All the classes, interfaces, packages, methods and fields of java
programming language are given according to java naming
convention.
Advantage of naming conventions in java
By using standard Java naming conventions, you make your code
easier to read for yourself and for other programmers. Readability of
Java program is very important. It indicates that less time is spent to
figure out what the code does.
Name Convention
class should start with uppercase letter and be a noun e.g.
name String, Color, Button, System, Thread etc.
interface should start with uppercase letter and be an adjective
name e.g. Runnable, Remote, ActionListener etc.
method should start with lowercase letter and be a verb e.g.
name actionPerformed(), main(), print(), println() etc.
variable should start with lowercase letter e.g. firstName,
name orderNumber etc.
package should be in lowercase letter e.g. java, lang, sql, util etc.
name
constants should be in uppercase letter. e.g. RED, YELLOW,
name MAX_PRIORITY etc.

Java OOPs Concepts


OOPs (Object Oriented Programming System)
Object means a real word entity such as pen, chair, table etc.Object-
Oriented Programming is a methodology or paradigm to design a
program using classes and objects. It simplifies the software
development and maintenance by providing some concepts:
o Object
o Class
o Inheritance
o Polymorphism
o Abstraction
o Encapsulation
Object
Any entity that has state and behavior is known as an object. For
example: chair, pen, table, keyboard, bike etc. It can be physical and
logical.
Class
Collection of objects is called class. It is a logical entity.
Class in Java
A class is a group of objects which have common properties. It is a
template or blueprint from which objects are created. It is a logical
entity. It can't be physical.
A class in Java can contain:
o fields
o methods
o constructors
o blocks
o nested class and interface
Syntax to declare a class:
1. class <class_name>{
2. field;
3. method;
4. }
Object and Class Example
In real time development, we create classes and use it from another
class. It is a better approach than previous one. Let's see a simple
example, where we are having main() method in another class.
We can have multiple classes in different java files or single java file.
If you define multiple classes in a single java source file, it is a good
idea to save the file name with the class name which has main()
method.
class Student{
int id;
String name;
}
class TestStudent2{
public static void main(String args[]){
Student s1=new Student();
s1.id=101;
s1.name="Sonoo";
System.out.println(s1.id+" "+s1.name);//printing members with a whit
e space
}
}
Inheritance
When one object acquires all the properties and behaviours of
parent object i.e. known as inheritance. It provides code reusability.
It is used to achieve runtime polymorphism.
Polymorphism
When one task is performed by different ways i.e. known as
polymorphism. For example: to convince the customer differently, to
draw something e.g. shape or rectangle etc.
In java, we use method overloading and method overriding to achieve
polymorphism.
Another example can be to speak something e.g. cat speaks meaw,
dog barks woof etc.
Abstraction
Hiding internal details and showing functionality is known as
abstraction. For example: phone call, we don't know the internal
processing.
In java, we use abstract class and interface to achieve abstraction.

Encapsulation
Binding (or wrapping) code and data together into a single
unit is known as encapsulation. For example: capsule, it is
wrapped with different medicines.
A java class is the example of encapsulation. Java bean is the fully
encapsulated class because all the data members are private here.

Advantage of OOPs over Procedure-oriented programming language


1)OOPs makes development and maintenance easier where as in
Procedure-oriented programming language it is not easy to manage
if code grows as project size grows.
2)OOPs provides data hiding whereas in Procedure-oriented
programming language a global data can be accessed from
anywhere.
3)OOPs provides ability to simulate real-world event much more
effectively. We can provide the solution of real word problem if we
are using the Object-Oriented Programming language.

Constructor in Java
Constructor in java is a special type of method that is used to
initialize the object.
Java constructor is invoked at the time of object creation. It
constructs the values i.e. provides data for the object that is why it is
known as constructor.
Rules for creating java constructor
There are basically two rules defined for the constructor.
1. Constructor name must be same as its class name
2. Constructor must have no explicit return type
Types of java constructors
There are two types of constructors:
1. Default constructor (no-arg constructor)
2. Parameterized constructor

Inheritance in Java
Inheritance in java is a mechanism in which one object acquires all
the properties and behaviors of parent object.
The idea behind inheritance in java is that you can create new classes
that are built upon existing classes. When you inherit from an existing
class, you can reuse methods and fields of parent class, and you can
add new methods and fields also.
Inheritance represents the IS-A relationship, also known as parent-
child relationship.
Why use inheritance in java
o For Method Overriding (so runtime polymorphism can be
achieved).
o For Code Reusability.
Syntax of Java Inheritance
1. class Subclass-name extends Superclass-name
2. {
3. //methods and fields
4. }
The extends keyword indicates that you are making a new class
that derives from an existing class. The meaning of "extends" is to
increase the functionality.
In the terminology of Java, a class which is inherited is called parent
or super class and the new class is called child or subclass.
Types of inheritance in java
On the basis of class, there can be three types of inheritance in java:
single, multilevel and hierarchical.
In java programming, multiple and hybrid inheritance is supported
through interface only. We will learn about interfaces later.
Note: Multiple inheritance is not supported in java through class.

When a class extends multiple classes i.e. known as multiple


inheritance. For Example:
Single Inheritance Example
File: TestInheritance.java
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class TestInheritance{
public static void main(String args[]){
Dog d=new Dog();
d.bark();
d.eat();
}}
Output:
barking...
eating...
Multilevel Inheritance Example
File: TestInheritance2.java
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class BabyDog extends Dog{
void weep(){System.out.println("weeping...");}
}
class TestInheritance2{
public static void main(String args[]){
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}}
Output:
weeping...
barking...
eating...
Hierarchical Inheritance Example
File: TestInheritance3.java
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class Cat extends Animal{
void meow(){System.out.println("meowing...");}
}
class TestInheritance3{
public static void main(String args[]){
Cat c=new Cat();
c.meow();
c.eat();
//c.bark();//C.T.Error
}}
Output:
meowing...
eating...

Q) Why multiple inheritance is not supported in java?


To reduce the complexity and simplify the language, multiple
inheritance is not supported in java.
Consider a scenario where A, B and C are three classes. The C class
inherits A and B classes. If A and B classes have same method and
you call it from child class object, there will be ambiguity to call
method of A or B class.
Since compile time errors are better than runtime errors, java renders
compile time error if you inherit 2 classes. So whether you have same
method or different, there will be compile time error now.
class A{
void msg(){System.out.println("Hello");}
}
class B{
void msg(){System.out.println("Welcome");}
}
class C extends A,B{//suppose if it were

Public Static void main(String args[]){


C obj=new C();
obj.msg();//Now which msg() method would be invoked?
}
}
Test it Now
Compile Time Error
Java static keyword
static keyword in java is used for memory management mainly. We
can apply java static keyword with variables, methods, blocks and
nested class. The static keyword belongs to the class than instance of
the class.
The static can be:
1. variable (also known as class variable)
2. method (also known as class method)
3. block
4. nested class

1) Java static variable


If you declare any variable as static, it is known static variable.
o The static variable can be used to refer the common property of
all objects (that is not unique for each object) e.g. company
name of employees,college name of students etc.
o The static variable gets memory only once in class area at the
time of class loading.
Advantage of static variable
It makes your program memory efficient (i.e it saves memory).
Understanding problem without static variable
1. class Student{
2. int rollno;
3. String name;
4. String college="ITS";
5. }
Suppose there are 500 students in my college, now all instance data
members will get memory each time when object is created.All
student have its unique rollno and name so instance data member is
good.Here, college refers to the common property of all objects.If we
make it static,this field will get memory only once.

Java static property is shared to all objects.

Example of static variable


1. //Program of static variable
2.
class Student8{
int rollno;
String name;
static String college ="ITS";

Student8(int r,String n){


rollno = r;
name = n;
}
void display (){System.out.println(rollno+" "+name+" "+college);}

public static void main(String args[]){


Student8 s1 = new Student8(111,"Karan");
Student8 s2 = new Student8(222,"Aryan");

s1.display();
s2.display();
3. }
4. }
Test it Now
Output:111 Karan ITS
222 Aryan ITS
next →← prev
this keyword in java
There can be a lot of usage of java this keyword. In java, this is
a reference variable that refers to the current object.
Usage of java this keyword
Here is given the 6 usage of java this keyword.
1. this can be used to refer current class instance variable.
2. this can be used to invoke current class method (implicitly)
3. this() can be used to invoke current class constructor.
4. this can be passed as an argument in the method call.
5. this can be passed as argument in the constructor call.
6. this can be used to return the current class instance from the
method.
Suggestion: If you are beginner to java, lookup only three usage
of this keyword.
1) this: to refer current class instance variable
The this keyword can be used to refer current class instance
variable. If there is ambiguity between the instance variables and
parameters, this keyword resolves the problem of ambiguity.
Understanding the problem without this keyword
Let's understand the problem if we don't use this keyword by the
example given below:
class Student{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee){
rollno=rollno;
name=name;
fee=fee;
}
void display(){System.out.println(rollno+" "+name+" "+fee);}
}
class TestThis1{
public static void main(String args[]){
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
1. }}
Test it Now
Output:
0 null 0.0
0 null 0.0
In the above example, parameters (formal arguments) and instance
variables are same. So, we are using this keyword to distinguish
local variable and instance variable.
Solution of the above problem by this keyword
class Student{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee){
this.rollno=rollno;
this.name=name;
this.fee=fee;
}
void display(){System.out.println(rollno+" "+name+" "+fee);}
}

class TestThis2{
public static void main(String args[]){
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
1. }}
Test it Now
Output:
111 ankit 5000
112 sumit 6000

Final Keyword In Java


The final keyword in java is used to restrict the user. The java final
keyword can be used in many context. Final can be:
1. variable
2. method
3. class
The final keyword can be applied with the variables, a final variable
that have no value it is called blank final variable or uninitialized final
variable. It can be initialized in the constructor only. The blank final
variable can be static also which will be initialized in the static block
only. We will have detailed learning of these. Let's first learn the
basics of final keyword.
Exception Handling in Java
The exception handling in java is one of the powerful mechanism
to handle the runtime errors so that normal flow of the application can
be maintaine
Hierarchy of Java Exception classes

Types of Exception
There are mainly two types of exceptions: checked and unchecked
where error is considered as unchecked exception. The sun
microsystem says there are three types of exceptions:
1. Checked Exception
2. Unchecked Exception
3. Error

Difference between checked and unchecked exceptions


1) Checked Exception
The classes that extend Throwable class except RuntimeException and
Error are known as checked exceptions e.g.IOException,
SQLException etc. Checked exceptions are checked at compile-time.
2) Unchecked Exception
The classes that extend RuntimeException are known as unchecked
exceptions e.g. ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException etc. Unchecked exceptions are not
checked at compile-time rather they are checked at runtime.
3) Error
Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError,
AssertionError etc.
Java Exception Handling Keywords
There are 5 keywords used in java exception handling.
1. try
2. catch
3. finally
4. throw
5. throws
public class Testtrycatch1{
public static void main(String args[]){
int data=50/0;//may throw exception
System.out.println("rest of the code...");
}
}
Test it Now
Output:
Exception in thread main java.lang.ArithmeticException:/ by
zero
Solution by exception handling
Let's see the solution of above problem by java try-catch block.
1. public class Testtrycatch2{
2. public static void main(String args[]){
3. try{
4. int data=50/0;
5. }catch(ArithmeticException e){System.out.println(e);}
6. System.out.println("rest of the code...");
7. }
8. }
Test it Now
Output:
Exception in thread main java.lang.ArithmeticException:/ by
zero
rest of the code...
Java Multiple catch block
If you have to perform different tasks at the occurrence of different Exceptions, use java
multi catch block.
Let's see a simple example of java multi-catch block.
1. public class TestMultipleCatchBlock{
2. public static void main(String args[]){
3. try{
4. int a[]=new int[5];
5. a[5]=30/0;
6. }
7. catch(ArithmeticException e){System.out.println("task1 is compl
eted");}
8. catch(ArrayIndexOutOfBoundsException e){System.out.println("t
ask 2 completed");}
9. catch(Exception e){System.out.println("common task completed
");}
10.
11. System.out.println("rest of the code...");
12. }

15:35

VIDEO LINKS
PlayList Link:
https://www.youtube.com/playlist?list=PLV_K8gHBuQuIJ-
lf8XWHRHd_8sPUJo9a0
Lecture 1:Java vs C++, Bytecode,Why Java is platform Independent?JAVA Tutorial for Beginners
Punjabi
CJ Singh Vlogs

Lecture 1.5: Keywords, Variables, Constant, Data Types, Operators, JAVA Tutorial for Beginners
CJ Singh Vlogs

Lecture 2:First Program In Java, How we can execute Java program?Java For Beginners in Punjabi.
CJ Singh Vlogs

Lecture 3: Java Installation And Path Setting. Java not recognized as internal or external command
CJ Singh Vlogs

Lecture 4: Java Command Line Arguments, Scanner Class, BufferedReader Class, Java In Punjabi
CJ Singh Vlogs

Lecture 5: Java Conditional Statements, if, else, if else, nested if,switch case,Java In Punjabi
CJ Singh Vlogs

Lecture 6: Java Loops/Iterative Statements while, do while, for loop , Java In Punjabi with subtitle
CJ Singh Vlogs

Lecture 9: Java , Array, Jagged Array, Labeled Break and Continue Learn in Punjabi.
CJ Singh Vlogs

Lecture 10: Java Class, Method with arguments Learn Java In Punjabi subtitle in English
CJ Singh Vlogs

Lecture 11: Java Constructor, Method Overloading, Constructor Overloading, Learn Java In Punjabi.
CJ Singh Vlogs

Lecture 12: Inheritance in Java, Constructor under inheritance, Super , Learn Java In Punjabi.
CJ Singh Vlogs

Lecture 13: Method Overriding, Final Variable, Final Method, Final Class, Abstract Method & Class.
CJ Singh Vlogs

Lecture 14:Static Keyword, Static Variable, Static Method, Static Block. ਜਾਵਾ ਪੰਜਾਬੀ ਭਾਸਾ ਵਵਚ ਵ ਿੱਖੋ
CJ Singh Vlogs

Lecture 15: Interface In Java, Multiple inheritance in java. ਜਾਵਾ ਪੰਜਾਬੀ ਭਾਸਾ ਵਵਚ ਵ ਿੱਖੋ
CJ Singh Vlogs

Lecture 16: Packages In Java, Public , private, Projected, Default access specifier of Java.
CJ Singh Vlogs

Lecture 17: Exception Handling in JAVA, try, catch, finally block, multiple catch and nested try
CJ Singh Vlogs

Lecture 18: User define Exception, Extend Exception Class, Creating subclass of Exception Class.
CJ Singh Vlogs
Lecture 19: String and StringBuffer Class in Java. Methods and Differnece of String and StringBuffer
CJ Singh Vlogs

Lecture 20: Multithreading in JAVA, Thread Class, Runnable Interface, Life Cycle of a Thread.
CJ Singh Vlogs

Lecture 21: yield(), sleep(), stop() methods in Multithreading in JAVA, synchronized method in Java
CJ Singh Vlogs

Lecture 22: File Handling in Java, File, FileReader, FileWriter, FileOutputstream, FileInputstream
CJ Singh Vlogs

Lecture 23: Applet in java, Appletviewer, Applet Life cycle of an applet, Applet tag.
CJ Singh Vlogs

Lecture 24: Graphics in Applet, Animation in java, drawRect, drawArc, drawOval, image in Applet.
CJ Singh Vlogs

Lecture 25: Frame in Java,Layout Manager, Grid Layout, Flow layout, Border layout, Null layout.
CJ Singh Vlogs

Lecture 26: Event handling in java , Action Listener, Event on Button Click, actionPerformed in Java
CJ Singh Vlogs

Lecture 27: CheckBox, Choice, Radio Controls,CheckboxGroup, ItemListener in Java


CJ Singh Vlogs

Lecture 28: KeyListener, MouseListener, MouseMotionListener Keyboard and mouse listener in java
CJ Singh Vlogs

You might also like