Unit-1 Java
Unit-1 Java
Around 1990 James Gosling , Bill roy and others at Sun Microsystems began
developing a language called Oak. They wanted it primarily to control
microprocessors embedded in consumer items such as cable set-top
boxes,VCR's, toasters, and also for personal data assistants (PDA).
The main problem with c and c++ is they are designed to be compiled for a
specific target(CPU)
Then the Internet and Web explosion began, so Sun shifted the target market
to Internet applications and changed the name of the project to Java.
Applets became popular and remain common but don't dominate interactive
or multimedia displays on web pages.
The term Java actual refers to more than just a particular language like C or
Pascal. Java encompasses several parts, including :
A high level language – the Java language is a high level one that at a
glance looks very similar to C and C++ but offers many unique features
of its own.
The Java virtual machine is the cornerstone of the Java and Java 2 platforms.
It is the component of the technology responsible for its hardware- and
operating system- independence, the small size of its compiled code, and its
ability to protect users from malicious programs
The Java virtual machine knows nothing of the Java programming language,
only of a particular binary format, the class file format. A class file
contains Java virtual machine instructions (or bytecodes) and a symbol table,
as well as other ancillary information
For the sake of security, the Java virtual machine imposes strong format and
structural constraints on the code in a class file. However, any language
with functionality that can be expressed in terms of a valid class file can be
hosted by the Java virtual machine. Attracted by a generally available,
machine-independent platform, implementors of other languages are turning
to the Java virtual machine as a delivery vehicle for their languages
The JVM is an imaginary CPU for which most Java compilers emit code.
Support for this imaginary CPU is what allows Java programs to run without
being recompiled on different CPUs. Nothing in the Java programming
language requires Java source code to be compiled into code for the JVM
instead of into native object code.
Versions of Java
1995: Version 1.0 of the Java Development Kit (JDK) was released for
free by Sun.
o 8 packages with 212 classes
o Netscape 2.0-4.0 included Java 1.0.
o Microsoft and other companies licensed Java.
1997: Version 1.1:
o 23 packages - 504 classes
o Improvements include better event handling, inner classes,
improved JVM.
oMicrosoft developed its own 1.1. compatible Java Virtual Machine
for the Internet Explorer.
o Many browsers in use are still compatible only with 1.1.
o Swing packages of greatly improved graphics became available
during this time but not included with the core language.
1999: Version 1.2, also called the Java 2 Platform
o 59 packages - 1520 classes
o Code and tools distributed as The Software Development Kit
(SDK)
o Java Foundation Classes (JFC), based on Swing, for improved
graphics and user interfaces, now included with the core
language.
o Collections API included support for various lists, sets, and hash
maps.
2000: Version 1.3:
o 76 packages - 1842 classes
o Performance enhancements including the Hotspot virtual
machine.
2002: Version 1.4:
o 135 packages - 2991 classes
o Improved IO, XML support, etc.
2004: Version 1.5 (previously numbered 1.5):
o 165 packages, over 3000 classes
o Faster startup and smaller memory footprint
o Metadata
o Formatted output
o Generics
o Improved multithreading features
Features
Here we list the basic features that make Java a powerful and popular
programming language:
Platform Independence
o The Write-Once-Run-Anywhere ideal has not been achieved
(tuning for different platforms usually required), but closer than
with other languages.
o Platform independence means both operating system independent
and hardware independent.
Object Oriented
1. Data encapsulation.
2. Data abstraction
3. Inheritance
4. Polymorphism
Compiler/Interpreter Combo
o Code is compiled to bytecodes that are interpreted by a Java
virtual machines (JVM) .
o This provides portability to any machine for which a virtual
machine has been written.
o The two steps of compilation and interpretation allow for
extensive code checking and improved security.
Robust
o Exception handling built-in, strong type checking (that is, all data
must be declared an explicit type), local variables must be
initialized.
Several dangerous features of C & C++ eliminated:
o No memory pointers
o No preprocessor
o Array index limit checking
Automatic Memory Management
o Automatic garbage collection - memory management handled by
JVM.
Security
o No memory pointers
o Programs runs inside the virtual machine sandbox.
o Array index limit checking
Dynamic Binding
o The linking of data and methods to where they are located, is
done at run-time.
o This differs from C++, which uses static binding. This can result
in fragile classes for cases where linked code is changed and
memory pointers then point to the wrong addresses.
Good Performance
o Interpretation of bytecodes slowed performance in early versions,
but advanced virtual machines with adaptive and just-in-time
compilation and other techniques now typically provide
performance up to 50% to 100% the speed of C++ programs.
Threading
o Lightweight processes, called threads, can easily be spun off to
perform multiprocessing.
o Can take advantage of multiprocessors where available
o Great for multimedia displays.
Built-in Networking
o Java was designed with networking in mind and comes with many
classes to develop sophisticated Internet communications.
You can choose from essentially two different programming environments for
Java:
Manual - with your favorite text editor (see below) create the Java
source code files (*.java) and then use the command line tools in the
Java Software Development Kit (SDK). The SDK is provided by Sun for
several platforms and includes a number of tools, the most important of
which are:
Examples:
// class identifier
public class MyClass
// variable identifier
int totalGrades;
// constant identifier
final double TAX_RATE = .05
No mouse support
No graphical/window support
No additional windows
Anti-virus programs that scan while the user is using the computer
Java GUI Applications:
These are the applications which supports the GUI by the creative use of
AWT and Swings .
Java allows you to create a GUI application that takes advantage of a rich set
of window and control types. If you are going to create an application that the
user works directly with, you will most likely want to create a GUI
application.
Java Applets
These are the programmes which are run with in a separate web
browser.
These are used to create small Graphical effects in Internet.
Java Applets allow you to imbed a program directly into a browser. The user
simply has to visit your website to view the applet. Applets can be used to
display graphics, animation and produce sound/music. Applets can be very
useful for displaying advertisements on web sites or providing a greater deal
of interactivity than an HTML page alone can provide
Package java.lang :
Provides classes that are fundamental to the design of the Java programming
language.
Package java.io
Provides for system input and output through data streams, serialization and
the file system.
Package java.util
Package java.applet
Provides the classes necessary to create an applet and the classes an applet
uses to communicate with its applet con
Package java.awt
Contains all of the classes for creating user interfaces and for painting
graphics and imagestext
Package java.net
Package javax.swing
Package java.sql
Provides the API for accessing and processing data stored in a data source
(usually a relational database) using the JavaTM programming language
Package java.rmi
Provides the classes and interfaces which are required for RMI (Remote
Method Invocation)package.
Package java.beans
Package java.text
Provides classes and interfaces for handling text, dates, numbers, and
messages in a manner independent of natural languages
Class classname
{
public static void main(String args[])
{
statements;
}
}
Example
Class HelloWorld
{
public static void main(String ar[])
{
System.out.println(“welcome to java world”);
}
}
javac HelloWorld.java
java HelloWorld
Tokens Of Java
In a Java program, all characters are grouped into symbols called tokens.
Larger language features are built from the first five categories of tokens
Keywords
Separators
; , . ( ) { } [ ]
Operators
An operator is a symbol which performs a particular operation.
Java supports all the types of operators supported in c language.
int Literals
double Literals
boolean Literals
char Literals
A char literal may be a single alphabet (either capital alphabet or
small alphabet).it must be represented in single quotes.
String Literals
Eg:String st=”welcome”;
Float Literals:
Float ft=12.34f;
Comments :
Line-Oriented: begins with // and continues until the end of the line.
Block-Oriented: begins with /* and continues (possibly over many lines)
until */ is reached.
Escape Sequences:
Escape
Meaning
Sequence
\n new line
\t horizontal tab
\v vertical tab
\b backspace
\r carriage return
\f form feed
\a bell
\\ \ (needed to denote \ in a text literal)
' (does not act as the right ' of a char
\'
literal)
" (does not act as the right " of a String
\"
literal)
data type:
Java has eight primitive types of data: byte, int, char, float, double, and
boolean.
Type Description
byte 8-bit twos-complement integer with values between –27 and 27–1 (–
128 to 127).
short 16-bit twos-complement integer with values between –215 and 215–1
(–32,768 to 32,767).
int 32-bit twos-complement integer with values between –231 and 231–1
(–2,147,483,648 to 2, 147,483,647).
long 64-bit twos-complement integer with values between –263 and 263–1
(–9,223,372,036,854,775,808 to 9,223,372,036,854,775,807).
float 32-bit single precision floating-point numbers using the IEEE 754-
1985 standard (+/– about 10power39).
double 64-bit double precision floating-point numbers using the IEEE 754-
1985 standard (+/– about 10power317).
The data types which are designed by using data abstraction is called
abstract data type.
Eg: Classes, interfaces, and arrays are known as reference types in Java.
The System class contains several useful class fields and methods. It cannot
be instantiated.
Field:
Package : java.io
Class : PrintStream
Method : println()
Syntax:
int n=10;
char ch='p';
float ft=12.345f;
double db=567.89;
java.io package:
Class Data Input Stream:
This class consists of methods and interfaces which are required for reading
data from the keyboard
Constructor Summary
DataInputStream(InputStream obj)
Creates a DataInputStream that uses the specified underlying
InputStream
ReadLine():
This method is used to read data from the keyboard in string format.
Syntax:
Class Integer:
The Integer class wraps a value of the primitive type int in an object. An
object of type Integer contains a single field whose type is int.
ParseInt():
import java.io.*;
class DataType2
int n;
float ft;
n=Integer.parseInt(dis.readLine());
ft=Float.parseFloat(dis.readLine());
Operators in java:
1.Arithmetic Operators:
3. Assignment Operators
= (equals to)
+=
-=
*=
/=
%=
&=
|=
^=
<<=
>>=
>>>=
Increment operators:
These operators are used to increment the given value by one
Decrement operators:
These operators are used to decrement the given value by one.
Conditional
&&
AND
Boolean
&
AND
Conditional
||
OR
Boolean
|
OR
Boolean
!
NOT
Boolean
^
XOR
6.Conditional operator
syntax:
Exp1?(Exp2):Exp3;
float a = b[3];
int n = 5;
char c=c[n];
Examples on operators:
Arithmetic operators:
import java.io.*;
class Operator1
int a,b;
a=Integer.parseInt(dis.readLine());
b=Integer.parseInt(dis.readLine());
System.out.println("Sum of given two values is:"+(a+b));
class Operator2
int a=10;
int b=a++;
a=10;
b=++a;
class Operator3
int a=10;
int b=a++;
a=10;
b=++a;
int a=4,b=5;
class Operator5
int a=4;
}
Example on Ternary Operator(or)Conditional Operator
import java.io.*;
class Operator2
int a,b,max;
a=Integer.parseInt(dis.readLine());
b=Integer.parseInt(dis.readLine());
max=(a>b)?a:b;
Control Statements are elements in Source Code that control the flow of
program execution.
Syntax:
If(exp)
{
statements;
}
If(exp)
{
statements-1;
}
else
{
statements-2;
}
3.nested if control statement
Syntax
If(Exp-1)
{
if(Exp-2)
{
|
|
if(Exp-n)
{
statements;
}
}
}
If(Exp-1)
{
statements-1;
}
else if(Exp-2)
{
statements-2;
}
else if(Exp-3)
{
statements-3;
}
|
|
|
|
else
{
statements-n;
}
Syntax:
Switch(var(or)Exp)
{
case value-1:
statements-1;
break;
case value-2:
statements-2;
break;
|
|
|
|
|
default:
default block statements;
}
Example 1:
import java.io.*;
class Condi1
{
public static void main(String ar[])throws IOException
int a,b,c,max;
a=Integer.parseInt(dis.readLine());
b=Integer.parseInt(dis.readLine());
c=Integer.parseInt(dis.readLine());
if(a>b)
if(a>c)
max=a;
else
max=c;
else
if(b>c)
max=b;
else
max=c;
Example 2:
import java.io.*;
class Condi2
int a,b,c,max;
a=Integer.parseInt(dis.readLine());
b=Integer.parseInt(dis.readLine());
c=Integer.parseInt(dis.readLine());
if((a>b)&&(a>c))
max=a;
else if(b>c)
max=b;
else
max=c;
import java.io.*;
class Switch1
int a,b,opt;
a=Integer.parseInt(dis.readLine());
System.out.println("Enter any b value:");
b=Integer.parseInt(dis.readLine());
System.out.println("Enter ur option:");
opt=Integer.parseInt(dis.readLine());
switch(opt)
case 1:
break;
case 2:
break;
case 3:
break;
case 4:
break;
case 5:
break;
default:
System.out.println("Invalid option");
1.break:
2.continue
Example
import java.io.*;
class Unconi
{
public static void main(String ar[])throws Exception
int n,i=0;
n=Integer.parseInt(dis.readLine());
while(i<=n)
i++;
if(i%2!=0)
continue;
System.out.println("\t"+i);
i=0;
while(i<n)
i++;
if(i%2==0)
continue;
System.out.println("\t"+i);
3.goto break
Arrays in java
Array:
An array is nothing but group of data items that belongs to
similar data type stored in continuous memory locations.
Declaration:
Syntax:
Datatype arrayname[]=new datatype[size];
Example:
int a[]=new int[3];
Initialization:
Syntax:
Datatype arrayname[]={value-1,value-2,…………………,value=n};
Eg:
int a[]={1,2,3};
Example:
import java.io.*;
class Array
int n,i;
n=Integer.parseInt(dis.readLine());
for(i=0;i<n;i++)
{
a[i]=Integer.parseInt(dis.readLine());
for(i=0;i<n;i++)
System.out.print("\t"+a[i]);
int b[]={1,2,3,4,5,6,7,8,9,10};
for(i=0;i<10;i++)
System.out.print("\t"+b[i]);
Declaration:
Syntax:
Data type Array name[][]=new int[row-size][column-size];
Initialization
Example:
import java.io.*;
class Array1
int r,c,i,j;
System.out.println("Enter no of rows:");
r=Integer.parseInt(dis.readLine());
System.out.println("Enter no of columns:");
c=Integer.parseInt(dis.readLine());
for(i=0;i<r;i++)
for(j=0;j<c;j++)
{
a[i][j]=Integer.parseInt(dis.readLine());
for(i=0;i<r;i++)
for(j=0;j<c;j++)
System.out.print("\t"+a[i][j]);
System.out.println();