What is Java?
Java is technology from Sun Micro Systems developed by James Gosling in 1991 with
initial name ‘Oak’. It was renamed to Java in 1995.
It is categories in three categories
1. Java Standard Edition (Java SE)
2. Java Enterprise Edition (Java EE)
3. Java Mobile Edition (Java ME)
Versions in Java
Java has two kind of versions
o Product Version
1.0
1.1
1.2
1.3
1.4
5.0
6.0
7.0
o Developer Version
1.0
1.1
1.2
1.3
1.4
1.5
6.0
7.0
Requirements
Softwares
Java Development Kit 1.5+
Java Runtime Environment 1.5+
IDE
Kawa
EditPlus
BlueJ
Eclipse
NetBeans (Sun)
Visual Age (IBM)
JDeveloper (Oracle)
Etc.
File Extension : .java
Features of Java
1. Simple
2. Secure
3. Object Oriented Programming
4. Portable
5. Platform Independent
a. Write Once, Run Anywhere
6. Multi-Threaded
7. Robust
a. Java provides big set of classes for almost every process
b. Built-in capabilities of Garbage Collection using Garbage Collector
c. Built-in capabilities of Exception Handling
Resource: http://java.sun.com
.java JAVAC .class (byte code) JVM(Code Verifier Just-in-time compiler
binary) Execution
JRE is comprises of Java Virtual Machine and Garbage Collector
Every Java program must have at least one class and every executable Java program must
have an entry point.
public static void main(String args[])
Conventions use in Java
- All keywords and packages in lower case
i. int, float, double etc.
ii. java.lang, java.io, java.awt, javax.swing etc.
- All methods and property starts with lower letter and every new word’s
first letter must be caps
i. length, readLine(), print(), println(), printf(), parseInt(), substring()
- All classes, interfaces etc. starts with caps
i. String, Math, BufferedReader, InputStreamReader
Writing First Java program
//First Java program as Test.java
class First
{
public static void main(String args[])
{
System.out.println("Welcome to Java");
}
}
Compiling the Program
JAVAC <programname>
Example
JAVAC Test.java First.class
Running a class
JAVA <classname>
Example
Java First
Note: If unable to run the class, add the current folder into the CLASSPATH variable
SET CLASSPATH=%CLASSPATH%;.
14.01.2009
Using Kawa Editor
F7 – Compile
F4 – Run
Terminologies in Java
Package
- A collection of related set of classes and interfaces
- java.lang
i. Default Package that provide generally used classes
1. System, String, Math, Integer, Float, Double etc.
- java.io
i. Provides classes related with File Handling and other input/output
operator
1. File, FileReader, FileWriter, InputStreamReader,
BufferedReader etc.
- java.awt
i. For GUI Programming in Java
1. Button, TextField, Checkbox, Menu etc.
- java.net
- java.util
- javax.swing
- javax.servlet
- javax.servlet.jsp
Using the package in a program
- Use import command
import <classname with package>;
Example
import java.io.BufferedReader;
import java.io.*;
Class
- A set of specification about an entity
- It contains a set of properties and methods
Object
- A real entity created based on class definition
Classname objectname=new Constructor();
Data Types in Java
- All data types in Java are signed
- Integrals
i. byte – 1byte
ii. short – 2 byte
iii. int – 4 bytes
iv. long – 8 bytes
- Floatings
i. float – 4 byte (6 dec place)
ii. double – 8 byte (14 dec. place)
- Booleans
i. boolean – 2 bytes
ii. Can have only true or false
- Characters
i. char – 2 bytes
Literals
- The values used directly without keyboard input
- Integral Literals
i. Default is int. Use L or l for long
ii. int n=5;
iii. long k=6L;
- Floating Literals
i. Default is double
ii. Use f or F for floats as suffix
1. double k=6.7;
2. float k=5.6; //error
3. float k=5.6f; //no error
- Boolean literals
i. Default is false
ii. boolean married;
iii. married=true;
- Character literals
i. Same as C
Reserve words in Java
1. Keyword
a. Words used by the language for some purpose
i. int, double, float etc.
2. Values
a. true, false, null
3. Reserve words for future
a. const, goto
Conditional Statements
1. if
2. switch
3. ternary operator (?:)
Looping Statements
- while
- do-while
- for loops
i. General for loop
ii. For-Each loop used with Arrays and collections
for(datatype variable : arrayname or collectioname)
{
Statements;
}
Example
//Using For-Each loop
class ForEachTest
{
public static void main(String args[])
{
int num[]=
{6,8,9,2,4,5
};
for(int i : num)
System.out.printf("%d\n",i);
}
}
Next Topics
Arrays
Reading Data from Keyboard
Wrapper Classes
Getting using Command Line
16.01.2009
Reading Data from Keyboard
- Data can be read using two modes
i. Interactive Mode
ii. Non-interactive or command line mode
- Interactive mode can be achieved using two methods
i. Using Scanner class of java.util package
ii. Using BufferedReader class of java.io package
Using Scanner class
- We need to define the location from which data to be read
Scanner sc=new Scanner(System.in);
Methods of Scanner class
String next()
int nextInt()
double nextDouble()
Example
- Get name and age of a person check for validity of voter
Importing Static Members of a Class
- use import static command
import static java.lang.System.*;
import static java.lang.Math.*;
Using BufferedReader class
- Data is passed from keyboard (System.in) and passed to an object of
InputStreamReader class which convert the stream of bytes to character
- These characters get passed to BufferedReader class for temporary
buffering until Enter key is pressed. A called readLine() of
BufferedReader is used to carry data from the buffer
i. String readLine()
- To convert data from string to numeric types Java provides special kind of
classes called as Wrapper classes
- Wrapper classes are the special classes corresponding to data types
i. byte Byte
ii. short Short
iii. int Integer
iv. long Long
v. float Float
vi. double Double
vii. char Character
viii. boolean Boolean
- These classes provides conversion functions as well as some additional
activities on their values
Conversion Formula
Datatype variable=WrapperClass.parseDatatype(stringdata);
Example
InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(isr);
int age=Integer.parseInt(br.readLine());
double basic=Double.parseDouble(br.readLine());
Non-interactive or Command Line Mode
- When passing data to a program from DOS prompt is called as command
line mode.
- Data is passed to args variable of main() method
Java VoterCmd Rakesh 45
void main(String args[])
{
}
args[0] Rakesh
args[1] 45
19.01.2009
Arrays
- An array is a variable that holds multiple values of similar type
- In Java arrays are treated as object
- Use new keyword to create the arrays
- Each array provides length property
Types of Arrays
1. Single Dimensional
a. int n[]=new int[5];
2. Two dimensional
a. int [][]n=new int[2][3];
Example
//Using Arrays
class ArrayTest
{
public static void main(String args[])
{
int num[]=new int[5];
num[0]=44;
num[1]=333;
num[2]=444;
num[3]=555;
num[4]=2222;
for(int i=0;i<num.length;i++)
System.out.println(num[i]);
}
}
Class and Objects
- A class is a set of specifications or template or blueprint about an entity
- A class contains a set of elements called members of a class
- Members in a class can be of two types
i. Static or Class members
ii. Non-static or instance members
- Static or class members can be access directly though the class name or by
instance. Use static keyword with such members.
- Non-static members always need an object to call them
- A class can be two categories of members
i. Fields
1. Variable
2. Constant
a. Use final keyword to define the constants
i. final double pi=3.14;
ii. Methods
Note: While naming the program name, if the program contains no public class then the
program name could be anything. If we define a class as public then program name and
class name must be same. A program can have many classes but only one can be public.
Static Blocks: special blocks that executes the code before main() and used to initialize
the static fields of a class
Example
class StaticTest
{
static
{
System.out.println("Hello");
}
public static void main(String args[])
{
System.out.println("Hi");
}
static
{
System.out.println("abc");
}
Types of Methods
1. General Methods
2. Abstract Methods
a. A method which has the signature but no body contents
b. Body is provided by the child class through overriding
c. Such methods can be declared in two places
i. Class
ii. Interfaces
d. If declared inside the class, use abstract keyword
e. If declared inside the interface, no keyword is required
3. Final Methods
Special method that can never be overridden
a. Use final keyword with such methods
Types of classes
1. General classes
2. Abstract class
a. Special class that can never be instantiated
b. They are always used for inheritance purpose only
c. An abstract class may or may not have any abstract method
d. If a class contains any abstract method the it must be declared as abstract
e. Use abstract keyword with such classes
3. Final class
a. A class that can never be inherited
b. Use final keyword with such classes
Assignment
Email: [email protected]
Q1: Create a class to manage information about the bank customers with the following
information
1. Account Number
2. Name
3. Current Balance
Add the method for
Constructor to create an object
Depositing the amount
Withdraw the amount
Check the balance
Create the menu for basic operations
1. Deposit the money
2. Withdraw the money
3. Show the Current Balance
4. Exit
21.01.2009
Object Oriented Programming in Java
- OOPs is a methodology for better project management
- It is based on four major concepts called as pillars of OOPs
i. Encapsulation
ii. Abstraction
iii. Polymorphism
iv. Inheritance
Encapsulation means combining all the members at one place.
class <classname>
{
//members
}
Abstraction is defined for controlling accessibility of class members and class itself. Java
provides four kinds of abstraction layers
Private – within the class
Public – anywhere access
Protected – in same or child class
Package or Default – within the package or folder
Introduction to Packages
- A package is a special folder that contains the classes for specific purpose
- Every class that get placed in a package must have package command on
top of it
i. package <packagename>;
- Java provides a big set of packages
i. java.lang (default)
ii. java.io
iii. java.util
iv. java.awt
v. java.net
vi. java.applet
vii. java.awt.event
viii. javax.swing
ix. javax.servlet
x. javax.servlet.jsp
xi. javax.servlet.jsp.tagext
Creating Custom Packages
1. create a folder to hold your packages somewhere on disc
2. create a folder with the package name in that folder
3. Save the classes with package command on top and
compile them
Using the custom packages
- First set the classpath for the folder having the packages
- For DOS
i. SET CLASSPATH=%CLASSPATH%;e:\mypackages
- For Kawa
i. Packages Classpath
Distributing the packages
- Packages are distributed as JAR or ZIP
- To create the zip file, go to the folder having the package, select all the
package with Ctrl+A and convert into zip file
23.01.2009
Distributing softwares in Java
1. JAR (Java Archive)
2. WAR (Web Archive)
3. EAR (Enterprise Archive)
Creating JAR file
- Use JAR tool from JDK\BIN folder
- Use the following options
i. c – Create
ii. t – Tabulate
iii. x – Extract
iv. v – Verbose
v. f – Filename
Create the JAR
JAR cvf <filename.jar> <filestoadd>
View the contents of JAR
JAR tvf <filename.jar>
Extract contents of a JAR
JAR xvf <filename.jar>
Converting a package folder into a JAR file
- Goto DOS Prompt
- Select the Drive having the package folder
- Issue the JAR command
i. JAR cvf <filename.jar> *.*
Polymorphism
- A concept that allows to do multiple operations by one item. It get
implemented by overloading.
- Java allows only method overloading
- Multiple methods with same name but different number of arguments or
the type of arguments
void area(int length, int width)
{
}
void area(double radius)
{
}
Inheritance
- Provides re-usability of code by reducing the code size hence reducing the
development time, cost as well as standardization of methods
- The class are categorized at three levels
i. Parents
ii. Super Class
iii. Current class
- Every Java class is child of java.lang.Object class
- Use extends keyword to inherit a class into other class
- Use JAVAP tool to view members of a class
- Use this keyword for current class objects and super keyword for super
class objects
-