CH1_1
CH1_1
Introduction to JAVA
What is Java?
Java is a Platform Independent Programming language
Any hardware or software environment in which a program runs, known as a platform. Since
Java has its own Runtime Environment (JRE) and API, it is called platform.
Java Version
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) ……………
What it is Used?
1. Desktop Applications such as acrobat reader, media player, antivirus etc.
2. Web Applications such as irctc.co.in..etc.
3. Enterprise Applications such as banking applications.
4. Mobile
5. Embedded System
6. Smart Card
7. Robotics
8. Games etc.
Types of Java Application?
There are mainly 4 type of applications that can be created using java:
1) Standalone Application
It is also known as desktop application or window-based application.
An application that we need to install on every machine such as media player, antivirus
etc.
AWT and Swing are used in java for creating standalone applications.
2) Web Application
An application that runs on the server side and creates dynamic page, is called web
application.
Currently, servlet, jsp, struts, jsf etc. technologies are used for creating web applications
in java.
3) Enterprise Application
An application that is distributed in nature, such as banking applications etc. It has the
advantage of high level security, load balancing and clustering.
In java, EJB is used for creating enterprise applications.
4) Mobile Application
An application that is created for mobile devices.
Currently Android and Java ME are used for creating mobile applications.
Brief History of JAVA
James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language project in June
1991.
originally designed for small, embedded systems in electronic appliances like set-top boxes.
initially called Oak and was developed as a part of the Green project
In 1995, Oak was renamed as "Java". Java is just a name not an acronym.
originally developed by James Gosling at Sun Microsystems(which is now a subsidiary of Oracle
Corporation) and released in 1995.
JDK 1.0 released in(January 23, 1996).
Features of Java
Simple
Java is simple in the sense that:
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 maintenace by providing some rulues.
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's a software-based platform that runs on top of other hardware-based platforms. It
has two components:
Runtime Environment & 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:
• No explicit pointer
• Programs run inside virtual machine sandbox.
• Class loader- adds security by separating the package for the classes of the local file
system from those that are imported from network sources.
• Byte code Verifier- checks the code fragments for illegal code that can violate access
right to objects.
• Security Manager- determines what resources a class can access such as reading and
writing to the local disk. Security can also be provided by through SSL, JAAS,
cryptography etc.
Robust
Java is Robust because –
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 set.
C/C++Program Execution
JVM:
JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides runtime
environment in which java bytecode can be executed.
JVMs are available for many hardware and software platforms (i.e. JVM is platform
dependent).
The JVM performs four main tasks:
Loads code
Verifies code
Executes code
Provides runtime environment
JVM provides definitions for the:
Memory area
Class file format
Register set
Garbage-collected heap
Fatal error reporting etc.
EX1: Program of swapping two numbers without using third variable and +,-.
1. javac: The Java compiler which converts Java source code into bytecode.
2. java: The Java application launcher which runs Java applications by starting the Java
Virtual Machine (JVM).
3. javadoc: A documentation generator which creates HTML documentation from Java
source code comments.
Syntax: javadoc filename
4. javap: The Java class file disassembler, used to view the contents of compiled class files.
The javap tool allows you to query any class and find out its list of methods and constants.
Syntax: javap [ options ] class
Example: javap java.lang.String
It is a disassembler which allows the bytecodes of a class file to be viewed when used with a
classname and the –c option.
Syntax: javap -c class
5. jdb: - jdb helps you find and fix bugs in Java language programs. This debugger has limited
functionality.
Syntax: jdb [ options ] [ class ] [ arguments ]
options : Command-line options.
class : Name of the class to begin debugging.
arguments : Arguments passed to the main() method of class.
Java comments
Java supports three types of comments that can be used to annotate the code: single-line comments,
multi-line comments, and documentation comments.
Single-Line Comments : Single-line comments start with // and continue to the end of the line. They
are typically used for brief explanations or notes.
Multi-Line Comments: Multi-line comments start with /* and end with */. They can span multiple
lines and are useful for longer explanations or temporarily disabling blocks of code.
Documentation Comments: Documentation comments start with /** and end with */. They are
used to generate API documentation and are typically placed before classes, methods, or fields. The
javadoc tool processes these comments to create HTML documentation.
Data Types
“Java Is a Strongly Typed Language.”
- Every variable has a type, every expression has a type, and every type is strictly defined.
- all assignments, whether explicit or via parameter passing in method calls, are checked for
type compatibility
- no automatic conversions of conflicting types.
- Any type mismatches are errors.
The Primitive Types:
- Java defines eight primitive types of data: byte, short, int, long, char, float, double, and
boolean.
- Integers/Numeric - includes byte, short, int, and long, which are for whole-valued
signed numbers.
- Floating-point numbers - includes float and double, which represent numbers with
fractional precision.
- Characters - includes char, which represents symbols in a character set, like letters and
numbers. Java uses Unicode to represent characters. Unicode defines a fully international
character set that can represent all of the characters found in all human languages. In Java
char is a 16-bit type (2 Bytes). The range of a char is 0 to 65,536.
- Booleans- Java has a primitive type, called boolean, for logical values. It can have only one
of two possible values, true or false.
2. BufferedReader Class: This is a more traditional method but involves more code. It requires
wrapping System.in with InputStreamReader and then with BufferedReader for efficient
reading. Reads text from a character-input stream.
import java.io.BufferedReader;
import java.io.InputStreamReader;
3. Command-Line Arguments: You can pass arguments directly when running the program. These
arguments are stored in the String args[] array of the main method.
public class CommandLineDemo {
public static void main(String[] args) {
if (args.length == 0) {
System.out.println("Please provide a name as argument");
return;
}
For(int i=0;i<args.length;i++)
{
System.out.println("Argument 1:”+args[i]);
}
}
}
EX2: Write a Program to accept two numbers and display result of arithmetic operations.
EX3: Write a Program to accept a number and display result of factorial of it.
.
Operators in Java
Java Operator Precedence
Operator Type Category Precedence
Unary postfix expr++ expr--
prefix ++expr --expr +expr -expr ~ !
Arithmetic multiplicative */%
additive +-
Shift shift << >> >>>
Relational comparison < > <= >= instanceof
equality == !=
Bitwise bitwise AND &
bitwise exclusive OR ^
bitwise inclusive OR |
Logical logical AND &&
logical OR ||
Ternary ternary ?:
Assignment assignment = += -= *= /= %= &= ^= |= <<= >>= >>>=
Switch Statement
- The switch statement works with byte, short, int, long, enum types, String and some wrapper
types like Byte, Short, Int, and Long.
- Java Switch Statement is fall-through. The Java switch statement is fall-through. It means it
executes all statements after the first match if a break statement is not present.
- Syntax:
switch(expression){
case value1:
//code to be executed;
break; //optional
case value2:
//code to be executed;
break; //optional
......
default:
code to be executed if all cases are not matched;
}
while
- The while loop is Java’s most fundamental loop statement.
- It repeats a statement or block while its controlling expression is true.
- Syntax:
while(condition)
{
// body of loop
}
- the body of the loop will be executed as long as the conditional expression is true.
- When condition becomes false, control passes to the next line of code immediately following
the loop.
- The curly braces are unnecessary if only a single statement is being repeated.
do-while
- .The do-while loop always executes its body at least once, because its conditional expression is
at the bottom of the loop.
- Syntax:
do {
// body of loop
} while (condition);
- Each iteration of the do-while loop first executes the body of the loop and then evaluates the
conditional expression.
- If this expression is true, the loop will repeat. Otherwise, the loop terminates.
for
- Java supports to forms of for
- Syntax 1:
for(initialization; condition; iteration)
{
// body
}
- Syntax 2:
for(type itr-var : collection)
statement-block
- type specifies the type and itr-var specifies the name of an iteration variable that will receive the
elements from a collection, one at a time, from beginning to end. The collection being cycled
through is specified by collection.
EX. Program to print even numbers between 1 to 100.
EX. Program to print multiples of 3 between 1 to 100.
Ex. Program to print the pattern
***** $* * * * $*** $
* * * $ * * $ $*
* * * $ * * $ *
* * * $ * * $ $*
***** ****$ $*** $
*
**
***
****
*****
****
***
**
*
EX. Program to print reverse of a number
EX Program to check a number is Armstrong or not
Arrays
- An array is a group of like-typed variables that are referred to by a common name.
- Arrays of any type can be created and may have one or more dimensions.
- A specific element in an array is accessed by its index.
- Arrays offer a convenient means of grouping related information.
One-Dimensional Arrays
- Syntax: array declaration is
type var_name[ ];
eg. int month_days[];
- type determines the data type of each element that comprises the array.
- to allocate memory a special operator new is used.
Var_name = new type[size];
eg. month_days = new int[12];
- to use new to allocate an array, you must specify the type and number of elements to allocate.
The elements in the array allocated by new will automatically be initialized to zero.
- in Java, all arrays are dynamically allocated.
- Arrays can be initialized when they are declared.
int month_days[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
- To find out how many elements an array has, use the length property:
Eg. System.out.println(month_days.length);
- Iterating through array:
1. We can loop through the array elements with the for loop, and use the length property
to specify how many times the loop should run.
eg.
for (int i = 0; i < month_days.length; i++) {
System.out.println(month_days [i]);
}
2. There is also a "for-each" loop, which is used exclusively to loop through elements in
arrays:
Syntax:
for (type variable : arrayname) {
...
}
eg.
for (int d : month_days) {
System.out.println(d);
}
Ex. Write a program to accept the array element and display in reverse order.
Ex. Write a program to accept the array element and display Sum and Average of elements in a
array.
Ex. Write a program to accept the array element and display Min and Max in a array.
Multidimensional Arrays
- In Java, multidimensional arrays are actually arrays of arrays.
- Syntax
dataType[][] arrayRefVar;
dataType [][]arrayRefVar;
dataType arrayRefVar[][];
dataType []arrayRefVar[];
eg.
int twoD[][] =new int[4][5];
OR
int twoD[][] = new int[4][];
twoD[0] = new int[5];
twoD[1] = new int[5];
twoD[2] = new int[5];
twoD[3] = new int[5];
- Jagged Array in Java : If we are creating odd number of columns in a 2D array, it is known as a
jagged array.
Eg.
int twoD[][] = new int[4][];
twoD[0] = new int[1];
twoD[1] = new int[2];
twoD[2] = new int[3];
twoD[3] = new int[4];
-
- EX: Write a java program to accept matrix and print its transpose.
- EX: Write a java program to accept matrix and row wise sum.
ADDITIONAL: Console Class (Java 1.5 and above): This class offers methods specifically for console
input/output. It can read text and passwords (without echoing characters)
import java.io.Console;