By : gaurav tiwari
Core Java Programming
PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR
What is JAVA
• Java is a high level Object Oriented programming
language.
• It is platform Independent Language means java
program are capable to run in any platform like
windows, Linux, Unix etc.
• Java is a high-level object-oriented programming
language developed by the Sun Microsystems.
PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR
Where java is used
• There are many Application where java is currently used.
Some of them are as follows:
A. Desktop Applications such as media player, antivirus etc.
B. Web Applications such as [Link], [Link] etc.
C. Enterprise Applications such as banking applications.
D. Mobile
E. Embedded System (telecom, smart cards ,missiles and
satellites , computer networking etc)
F. Robotics
G. Games etc.
PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR
Where java is used
Web Application
& Enterprise
Application
(J2EE)
Standalone Mobile
Application Application
(J2SE) (J2ME)
PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR
Java
• James Gosling, Mike Sheridan, and Patrick Naughton initiated the
Java language project in June 1991. The small team of sun engineers
called Green Team.
• Originally designed for small, embedded systems in electronic
appliances like set-top boxes TV,VCR etc.
• Firstly, it was called "Greentalk" by James Gosling and file extension
was .gt.
• After that, it was called Oak and was developed as a part of the
Green project.
PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR
Java
• In 1995, Oak was renamed as "Java .
• Notice that Java is just a name not an acronym.
• Originally developed by James Gosling at Sun Microsystems.
• In 1995, Time magazine called Java one of the Ten Best Products of
1995.
• JDK 1.0 released in(January 23, 1996).
PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR
Features of Java Language
• Simplicity
• Object Oriented
• Platform Independent
• Distributed
• Robust & Secure
• Multi-Threaded
• Compiled and Interpreted
PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR
Installation of Java
1. First Of all you have a .exe file of Jdk1.7(if
not Then Download from Oracle Site).
2. Now this exe file can be save anywhere (let
us consider D:\ drive)
3. Open d:\ drive and double click on jdk1.7
exe file.
4. Press Next button until complete.
5. Now check the java where it is installed
6. If successfully installed java then go to the
path where java is installed
7. C:\program File(X86)\java\jdk1.7
PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR
• Doble click on the java installation exe file
• Click Next Button
• Then again select Next Button
• Cloick next button
• Now close the button press
Set the Path of Java
1. Go to C:\program
File(X86)\java\jdk1.7\ i location and
copy it
1. Ope Desktop a d sele t the o puter
icon -> right li k a d sele t the properties
Optio .
1. No sele t Ad a e “yste “etti gs o
left Pane
1. Click the Environment Variables button and
then
1. Click on new Button and then provide a
alue Varia le a e a d Varia le alue
2. Variable name=Path
3. Variable value=copy the path of java from
bin(C:\Program Files(X86)\Java\Jdk1.7\bin)
and paste text box.
1. Set the path
• Now type the javac command
First Example of Java
1. Open Notepad
Type a simple hello Java Program
1. Save As [Link] in anywhere suppose
(D:\javaProgram\[Link])
Open the Command Prompt
• Window icon--cmd- and then Enter
Button of key board
• Now go to java source file location where java
programs are saved
• Now Type the Java Compiler command with
javac [Link]
• Now check the .class file generated by
compiler in that Location
• Now run the java Program by the command
of ja a file a e a d “ee the output
Hello Java
Co piled & I terpreted…
• Java programs are executed by an interpreter, so
it’s relatively easy to fi d errors i a progra .
• When a running program encounters a problem,
the Java interpreter will display a meaningful
message and , if necessary stop the program.
PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR
Co piled & I terpreted…
Source Code
Implementation of
Java Program
Java Compiler
Byte code
Windows Macintosh
Interpreter Interpreter
Machine Code Machine Code
Windows Windows
Computer Computer
PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR
Java Architecture…
• The Java Language and run time environment were
designed to facilitate network computing .
• The java design team wanted java to be able to create
flexible and highly reliable programs that could be
distributed across networks and run on virtually any
computing platform. Java uses unicode character set.
Java source files are later compiled to Byte -
code file.
PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR
Bytecode…
• Byte-code is a standardized machine independent,
low level language. The byte code files are loaded
a d i terpreted at the lie t’s a hi e y a spe ial
program called Java Virtual Machine(JVM).
• For Example : An HTML document downloaded to
your machine by a browser might embed a Java
data entry applet. When we activate this applet,
the byte code files are executed by the browser's
JVM.
PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR
Bytecode…
• When a user runs a Java Program , it is upto the
JVM to load, possibly verify and then execute it.
• The JVM can perform this function from within a
browser or any other container program or directly
on top of the operating system.
PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR
What actually JVM does...
• It validates the requested byte codes verifying that
they pass various formatting and security checks.
This is a security feature known as
Byte-code-verifier.
• It allocates memory for the incoming Java class
files and guarantees that the security of JVM is not
violated. This is known as class loader.
• It interprets the byte-code instructions found in
the class files to execute the program.
PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR
Java Development Kit...
• The JDK comes with a collection of tools that are
used for developing and running Java Programs.
• Appletviewer (for viewing Java applets)
• javac (Java compiler)
• java (Java Interpreter)
• javap ( Java diassembler)
• javah (for C header files)
• jdb (Java debugger)
Programming in Java...
Java offers basic two flavours of
programming.
A) Application
B) Applets
PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR
Application...
• Applications have no special support in HTML for
embedding or downloading.
• Applications can be executed from the command
line with a small utility such as [Link] or
[Link]
• Applications have no inherent security restrictions.
• Application are usually system level programs i.e.
these programs run in the background and
or ally do ’t i volve i user i tera tio . For
example : Server adminstration ,Security manager.
PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR
Applets...
• Applets can be embedded in HTML pages and
downloaded over the internet or intranet.
• Applets can only be executed inside a Java
compatible container, such as modern Web
Browser.
• Applets execute under strict security limitations
that disallow certain operations, such as accessing
files or syste servi es o the user’s o puter.
PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR
Applets...
• Applets are the programs written specially for
distribution over a network .
• These programs contain information to be
delivered to the world and involve user
interaction, for example : Order entry form ,
Registration form.
PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR
Application & Applets...
Java
Source
Code
Java
Applet Compiler
Application Type
Type
Java Enabled
Java Interpreter
Web Browser
Output Output
PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR
First Java Application Program...
import [Link].*;
class Firstapp
{
public static void main(String args[ ])
{
“yste .[Link] tl This is First Appli atio ;
}
}
PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR
First Java Application Program...
• Explanation:
• For most computer languages, the name of file
that holds the source code to a program is
arbitrary. However this is not the case with Java.
The first thing you must learn about Java is that
the name you give to a source file should match
the name of the class holds the main() method. So,
in our case name of program is none other than
[Link]. This is because the source file is
officially called a compilation unit. Extension is
also four character long, so your OS must support
long extensions.
PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR
First Java Application Program...
Explanation:
First statement import [Link].*;
The purpose of this statement to instruct
interpreter to load language package lang.
Second statement class Firstapp
Declares a class name firstapp so as to place
everything inside this class.
Third statement public static void main(String args[ ])
Defines a method main. This is the starting point for
PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR
First Java Application Program...
• the interpreter to begin the execution of program.
Here public is an access specifier that declares the
main method as unprotected and therefore making it
accessible to all other classes.
• Next appears the keyword static which declares
this method as one that belongs to the entire class
and not a part of any objects of the class. The main
must always be declared as static since the interpreter
uses this method before any objects are created. The
type modifier void states that main method does not
return any value.
PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR
First Java Application Program...
• In main(), there is only one parameter String args[ ]
• declared a parameter named args, which is an
array of objects of the class String. Objects of type
String store character strings. args receives any
command-line arguments present when the
program is executed. This program does not make
use of this information.
PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR
First Java Application Program...
• Fourth statement is
“yste .[Link] tl This is First Appli atio ;
• The println mehtod is a member of the out object,
which is a static data member of System class. This
line prints the string to the screen. The method
println always appends a newline character to the
end of the string. So for the output to be printed
on the same line use print in place of println.
PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR
First Java Application Program...
• To compile the Java program, execute the compiler, javac,
specifying the name of the source file on command line:
• C:\> javac [Link]
• The javac compiler creates a file called
[Link] that contains the bytecode version
of the program. The bytecode is the intermediate
representation of your program that contains
instructions the Java Interpreter will execute. So,
to run your program you use Java interpreter java.
• C:\> java Firstapp
PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR
First Java Application Program...
• When Java source code is compiled each
individual class is put its own output file named
after the class and using the .class extension. This
is why it is important to give source the same
name as the class they contain, so when you
execute your program you are actually executing
the class by the interpreter. It will automatically
search for a file by that name that has the .class
extension. If it finds the file, it will execute the
code contained in the specified class.
PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR
JAVA
.It can be used to create following Application.
Web Application
& Enterprise
Application
(J2EE)
Standalone Mobile
Application Application
(J2SE) (J2ME)
Type a simple hello Java Program
4. Understanding of First java Program.
class is used to declare a class in java.
public is an access modifier which represents visibility, it
means it is visible to all.
static is a keyword, if we declare any method as static, it is
known as static method. The core advantage of static method
is that there is no need to create object to invoke the static
method. The main method is executed by the JVM, so it
doesn't require to create object to invoke the main method.
So it saves memory.
4. Understanding of First java Program.
void is the return type of the method, it means it doesn't
return any value.
main represents startup of the program means control start
execution from main method because it is program startup
method so its name is main .
String[] args is used for command line argument.
[Link]() is used print statement where system is
predefine class . Out is reference variable of system class and
println() is predefine method.
COMPILER
A compiler is a translator s/w that takes as input the
source program written in high level language and convert
it into equivalent Byte code.
It also checks for syntax errors in program.
SOURCE Byte
COMPILER (javac)
CODE Code
Bytecode
• Java Source programs are translated into an
intermediate language called bytecode.
• Bytecode is the same no matter which computer
platform it is run on.
• Bytecode is translated into native code that the
computer can execute on a program called the JVM.
• The Bytecode can be executed on any computer
that has the JVM. Hence Java’s slogan, “Write
once, run anywhere”.
INTERPRETER(Java)
A interpreter is a translator s/w that takes as input the source
program written in high level language and convert it into
equivalent m/c code or object code, and immediately execute
the code.
Byte INTERPRETER
(java) JVM
CODE
Output
[Link] Development Kit
What is JDK ?
It is software bundled that consists Java API and Run Time
Environment.
JDK is an acronym for Java Development Kit. It physically exists. It
contains JRE + development tools(javac ,java, javap etc.).
1. Java Virtual Machine (JVM)
1) JVM (Java Virtual Machine) is an abstract machine. It is a
specification that provides runtime environment in which
java byte code can be executed.
2) JVMs are available for many hardware and software
platforms ([Link] is platform dependent).
3) The JVM performs four main tasks:
Loads code
Verifies code
Executes code
Provides runtime environment
Java source code to Final Output
Source File
(.java)
Loads code
Compiler
(javac) Verifies code
Executes code
Provides runtime
environment
Class File
(.class)
Access Run
Interpreter Time
(java)
Environment
(JRE)
Final Out put
The Java file Transformation
Windows PC
Running JVM
Java Program Java Compiler Java Bytecode Unix Running
(*.java) Javac (*.class) JVM
Macintosh
Running JVM
Core Java Programming
Data-types and Variables
PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR
Keywords in Java...
• There are 49 reserved keywords currently defined
in the Java language. These keywords, combined
with the syntax of the operators and separators,
form the definition of the Java language. These
keywords cannot be used as names for a variable,
Class, or method.
PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR
Data Types in Java...
PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR
Data Types in Java...
Data Type Default Value Default size
boolean false 1 bit
• char '\u0000' 2 byte
byte 0 1 byte
short 0 2 byte
int 0 4 byte
long 0L 8 byte
float 0.0f 4 byte
double 0.0d 8 byte
PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR
Range of Data Types…
Data Type Range
byte -128 to 127
short -32768 to 32767
int -2,147,483,648 to 2,147,483,647
long -9,223,372,036,854,775,808 to
9,223,372,036,854,775,807
float 3.4e-038 to 3.4e+038
double 1.7e-308 to 1.7 e+308
char 0 to 65535
PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR
Identifiers in Java...
• Identifiers are the names of variables , methods ,
classes , packages and interfaces. Identifiers must
be composed of letters , numbers , the underscore
and the dollar sign.$.
• They cannot contain white spaces, Identifiers may
only begin with a letter, the underscore or a dollar
sign. You cannot begin a variable name with a
number. All variable are case sensitive for example
• MyVariable is not same as myVariable
PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR
Identifiers in Java...
• They cannot contain white spaces.
• Identifiers may only begin with a letter, the
underscore or a dollar sign.
• You cannot begin a variable name with a number.
• All variable are case sensitive for example
MyVariable is not same as myVariable
PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR
Invalid Identifier Names...
• My Variable // contains a space
• 9pins // Begins with a digit
• a+b // the plus sign is not an alphanumeric
character
• testing 1-2-3 // should be underscore
PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR
Java Variables...
• Variable is name of reserved area allocated in
memory.
• Variable is the value that can varies in program
• The following lines show how to create variables
of integer types :
• long My_First_Byte = 10;
• int a=20;
PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR
Integer Variables...
• The following lines show how to create variables
of integer types :
• long My_First_Byte = 10;
• int a=20;
PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR
Boolean Variables...
• A Boolean Variable is not a number. It can have
one of two values true or False. There are two
ways to set its values .
• The first way to do this is explicitly.
• Ex :a) boolean firstboolean = false;
• b) boolean firstboolean = secondboolean;
PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR
Float & Double Variables...
• In Java, floating point numbers are represented by
the types float and double . Both of these follow a
standard floating point specification.
• float a = 35.6f; double x = 356556.25;
• float b = 35.7F; double y = 356556.25;
• a,b,x,y are variables.
• Note : 35.6f and 35.7F are single Precision Literals.
As Floating point numbers are treated as double
precision quantities. To force them to single
precision we use f and F.
PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR
Java Constant...
• Constant is the value that can not change during
program execution.
• You can make a variable into constant using final
keyword.
• For example :
• final int x=5;
• x=x+1 // compile time error
PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR
Java Control
Structure
Branching Looping
Unconditional a. while
Conditional
a. break b. do while
a. if else
b. Continue c. for
b. Multiple if
c. return d. Labeled for
c. Nested if else
loop
d. else if ladder
e. Enhance
e. switch
loopKANPUR
PRANVEER SINGH INSTITUTE OF TECHNOLOGY,
Control Structures...
if-else Statement
if (condition)
{
statement1;
}
else
{
statement2;
}
PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR
Control Structures...
Write a java program to print any person is eligible
for vote or not .
public class vote
{
public static void main(String args[])
{
int a=19;
if(a>=18)
{
[Link]("eligible for vote");
}
else
{
[Link]("note eligible for vote");
}
}
}
PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR
Control Structures...
1. Java Program to Swap Two Numbers with third variable .
2. Java Program to Swap Two Numbers without third variable
3. Java Program to find area of circle .
4. Java Program to find area of Triangle .
5. Write a java program to print given number is even or odd.
(number%2==0)
6. Write a java program to find greatest number between two
number.(number1>number2)
7. Write a java program to find given year is leap or not .
8. Write a java program to print given character is vowels or
consonant.
PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR
Control Structures...
If the condition is true, then statement1 is
executed. Otherwise, statement2 (if it exists) is
executed. In no case will both statements be
executed.
Nested ifs
A nested if is an if statement that is the target
of another if or else. Nested ifs are very common in
programming. When you nest ifs, the main thing to
remember is that an else statement always refers to
the nearest if statement that is within the same
PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR
Control Structures...
block as the else and that is not already
associated with an else.
if(i == 10) {
if(j < 20) a = b;
if(k > 100) c = d; // this if is
else a = c; // associated with this
else
}
else a = d; // this else refers to if(i == 10)
PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR
Control Structures...
The if-else-if Ladder
A common programming construct that is
based upon a sequence of nested ifs is the if-else-if
ladder. It looks like this:
if(condition) statement;
else if(condition) statement;
else if(condition) statement;
.
.
.
else statement;
PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR
Control Structures...
• The if statements are executed from the top down.
• As soon as one of the conditions controlling the if
is true, the statement associated with that if is
executed, and the rest of the ladder is bypassed.
• If none of the conditions is true, then the final else
statement will be executed.
• The final else acts as a default condition; that is, if
all other conditional tests fail, then the last else
statement is performed.
• If there is no final else and all other conditions are
false, then no action will take place.
PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR
Control Structures...
class IfElse {
public static void main(String args[ ]) {
int month = 4; // April
String season;
if(month == 12 || month == 1 || month == 2)
season = "Winter";
else if(month == 3 || month == 4 || month == 5)
season = "Spring";
else if(month == 6 || month == 7 || month == 8)
season = "Summer";
else if(month == 9 || month == 10 || month == 11)
season = "Autumn";
else
season = "Bogus Month";
[Link]("April is in the " + season + "."); } }
O/P: April is in the Spring
PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR
Control Structures...
switch
The switch state e t is Ja a’s ulti ay ra h
statement. It provides an easy way to dispatch
execution to different parts of your code based on the
value of an expression. As such, it often provides a
better alternative than a large series of if-else-if
statements.
switch (expression) {
case value1: // statement sequence break;
case value2: // statement sequence break;
.
case valueN: // statement sequence break;
default: // default statement sequence break; }
PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR
Control Structures...
// A simple example of the switch.
class SampleSwitch {
public static void main(String args[ ]) {
int i=5;
switch(i) {
case 0: [Link]("i is zero."); break;
case 1: [Link]("i is one."); break;
case 2: [Link]("i is two."); break;
case 3: [Link]("i is three."); break;
default: [Link]("i is greater than 3."); break;
}}}
PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR
Control Structures...
The break statement is optional. If you
omit the break, execution will continue on into
the next case. It is sometimes desirable to have
multiple cases without break statements
between them.
class MissingBreak {
public static void main(String args[]) { int i = 7;
switch(i) {
case 0: case 1: case 2: case 3: case 4:
[Link]("i is less than 5"); break;
case 5: case 6: case 7: case 8: case 9:
[Link]("i is less than 10"); break;
default:
[Link]("i is 10 or more"); }}}
PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR
Iteratio State e ts…
Ja a’s iteratio state e ts are for, while, and do-
while.
while
The hile loop is Ja a’s ost fu da e tal loopi g
statement. It repeats a statement or block while its
controlling expression is true. Here is its general
form:
while (condition) {
// body of loop }
PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR
Iteratio State e ts…
do-while
The do-while loop always executes its body at
least once, because its conditional expression is at
the bottom of the loop. Its general form is
do {
// body of loop
} while (condition);
PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR
Iteratio State e ts…
for
Here is the general form of the for statement:
for(initialization; condition; iteration) {
// body }
class ForTick {
public static void main(String args[ ]) {
int n;
for(n=10; n>0; n--)
[Link]("tick " + n); } }
PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR
Iteratio State e ts…
Using break to Exit a Loop
class BreakLoop {
public static void main(String args[]) {
for(int i=0; i<100; i++) {
if(i == 10) break; // terminate loop if i is 10
[Link]("i: " + i); }
[Link]("Loop complete."); } }
O/P: Prints i=0 to i=9 afterwards terminates loop.
PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR
Iteratio State e ts…
continue
Sometimes it is useful to force an early
iteration of a loop. That is, you might want to
continue running the loop, but stop processing the
remainder of the code in its body for this particular
iteration. This is, in effect, a goto just past the body
of the loop, to the loop’s e d. The co ti ue
statement performs such an action.
PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR
Iteratio State e ts…
class Continue {
public static void main(String args[]) {
for(int i=0; i<10; i++) {
[Link](i + " ");
if (i%2 == 0) continue;
[Link](""); } } }
O/P: Prints Odd and Even numbers with new line
return
The return statement is used to explicitly return
from a method. That is, it causes program control to
transfer back to the caller of the method.
PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR
Iteratio State e ts…
At any time in a method the return statement can be
used to cause execution to branch back to the caller
of the method. Thus, the return statement
immediately terminates the method in which it is
executed.
In our program return causes execution to return to
the Java run-time system, since it is the run-time
system that calls main( ).
PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR
Iteratio State e ts…
class Return {
public static void main(String args[]) {
boolean t = true;
[Link]("Before the return.");
if(t) return; // return to caller
[Link]("This won't execute.");
}}
PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR