0% found this document useful (0 votes)
93 views

Unit I Introduction

Java was invented in 1991 at Sun Microsystems by James Gosling and others. It is an object-oriented language that is simple, robust, architecture neutral, interpreted, high-performance, multithreaded, distributed, and dynamic. Java uses a runtime interpreter called the Java Virtual Machine (JVM) which allows Java programs to run on any device. This portability, along with security features for applets, made Java popular for internet programming.

Uploaded by

reddy
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
93 views

Unit I Introduction

Java was invented in 1991 at Sun Microsystems by James Gosling and others. It is an object-oriented language that is simple, robust, architecture neutral, interpreted, high-performance, multithreaded, distributed, and dynamic. Java uses a runtime interpreter called the Java Virtual Machine (JVM) which allows Java programs to run on any device. This portability, along with security features for applets, made Java popular for internet programming.

Uploaded by

reddy
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 15

Introduction

History of java: Java was invented by James Goslings, Patrick Naughton, Chris
Warth, Ed Frank, and Mike Sheridan at Sun Microsystems, Inc in 1991. This language is
earlier called as “OAk” has renamed to java in 1995.

The java Buzzwords or the features of java:


The features of java can be listed as follows.
1) Simple
2) Object oriented
3) Robust
4) Architecture Neutral
5) Interpreted and High performance
6) Multithreaded
7) Distributed
8) Dynamic

Simple: Java inherits the c/c++ langue syntax to some extent. This makes the
programmer easier in learning this language. So java is defined as simple.

Object oriented: Every entity can be treated as an object and build functionalities
around it. It also makes easy to extend the functionalities around these object. And
since java follows these principles of the object oriented, it is called as an object
oriented programming language.

Robust: Robust means able to with stand in all critical conditions.


These below things make java a robust language.
1) Exception handling: some of the errors that occur during the program execution
are hard to handle. Java provides an exception handling api(Application
Programming Interface) for handling the divide by zero kind of exceptions which
abruptly stop the program execution
2) Compile time errors- Java is a Strictly typed language. It does a compile time
check to find the code syntax errors.
3) Memory management- java provides automatic allocation and deallocation of
memory, which is know as garbage collection, whereas in case of c++ language
the deallocation of the memory has to be done by programmers by writing
destructors in their programs.
All these features make java a robust language.

Architecture Neutral: Java uses a runtime interpreter called JVM(Java Virtual


Machine) which makes the java compiled programs executable.
So java has a slogan as “write once run anywhere”(WORA). Ex: Java program
compiled on windows can be executed on Unix platform. So java is also called as
portable language.
Interpreted and High performance: Java is compiled into an intermediate bytecode
program by the jvm. This byte code is interpreted line by line easily into the native
machine code. So java is called a high performance language.

Multithreaded: Using java we can create interactive programs, which needs multiple
processes to be done in parallel. Java provides the api for multithreading to achieve
the smoothly running interactive systems.

Distributed: Java can work in the distributed environment(systems distributed over


the network), which made it popular as an internet programming language. Also
handles the TCP/IP protocols and supports RMI(Remote method invocation).

Dynamic: Java can verify and resolve objects at runtime and updates the bytecode
dynamically. This is one feature of called applet programming.

Importance of java to internet:


Java supports two kinds of programming 1) Application programming & 2) Applet
Programming.
An applet is a small piece of executable code that can be transmitted over the internet
and executed automatically in the java enabled web browser. It is not simply a sound
or image file i.e. downloaded onto your system, but is an interactive program.
This java enabled web browser will not allow the applet to open or interact with any
other file on your hard disk. An applet will only interact with the server from which it
is downloaded.
Because of this kind of security provided by java, we can download an applet on to
any kind of platform.
Thus java became popular to internet.

Object oriented programming principles:


The essential elements of object oriented programming are listed below:-
1) Class
2) Object
3) Encapsulation
4) Abstraction
5) Inheritance
6) Polymorphism

Class & object : An Object is anything that is of some interest to an application


under development. An object may represent an real time entity or an event.
For Example in a banking application, an account holder is an object. Account holder
name, account number, account balance etc are attributes and cash withdrawal, cash
deposit are the operations.

A class can be considered as the general description of an object. A class doesn’t


exists in memory, but the objects created will exists in memory.
Ex: A class is like a blue print of a building and the object is its physical
representation (the building itself).

A class holds the data and the methods which operate on that data.
In object oriented terminology data is referred as attributes and methods as
operations.

Encapsulation: The binding of data and the methods together, so that the external
entities cannot modify the data is called encapsulation. In java a class encapsulates
the data and methods by defining the data as private in the class.
This is also defined as data hiding.

Abstraction: This is one of the essential principle of OOP. Considering only the
essential elements by eliminating the unnecessary things is called abstraction.
For ex: When we use a car, we are not bothered about its inner alignment of the
machine parts, but try to know about the gear, accelerator or break. Therefore the
complexity involved in making a car reduced by knowing only the essential elements.

Inheritance: The process of acquiring properties of one object for the purpose of the
another object is called inheritance. The existing code is reused without rewriting it
hence avoiding code redundancy.

Polymorphism: Polymorphism means many forms. Ex: Car is a generic name for
maruthi 800 or a wagoanR or Accent Hyundai. But each car has different
specifications of speed, milage etc.

First Java Program:

Save as “HelloWorld.java”
class Helloworld
{
public static void main(String args[]){
System.out.println(“Hello World”);
}
}

main is the method where from the execution starts.


void- since main method doesn’t return anything it return type is void.
static - a method can be called without an object if it is declared as static.
public- main method should be public to be accessed outside the class.

Execution: Save the given file as HelloWorld.java and open the command
prompt.Type the below command
Compiling command d:\javac HelloWorld.java
The compilation process will convert the program to the intermediate byte code file
which has the extension .class. This file has to be interpreted by jvm to get the out.

If any compile time errors will be displayed in the console. If no errors, the command
prompt is ready for the next command . The run the program using the below
command.
Running command d:\java HelloWorld

Output : Hello World

Data Types: Java defines both primitive and non-primitive datatypes.


Java defines 8 primitive data types that are listed below.

S.No Data type Value Range


1. byte - 8-bit signed integer -128 to 127
2. short - 16-bit signed integer -32,768 to 62,767
3. int - 32-bit signed integer -2,147,483,648 to 2,147,483,647
4. long - 64-bit signed integer -9,223,372,036,854,775,808 to
9,223,372,036,854,775,807
5. char - 16-bit Unicode 0 to 65536
6. float - 32-bit floating point 1.4e-045 to 3.4e+038
7. double - 64-bit floating point 4.9e-324 to 1.8e+308
8. boolean- either ture/false

1) byte - 8-bit signed integer


2) short - 16-bit signed integer
3) int - 32-bit signed integer
4) long - 64-bit signed integer
5) char - 16-bit unicode
6) float - 32-bit floating point
7) double - 64-bit floating point
8) Boolean - either true/false

The non-primitive data types are class, array, Strings etc.

Variables: The unit of storage which can modify its data anytime during the
execution of the program are called variables.

Syntax of declaring a variable:


Type identifier [=value][, identifier[=value]…];

Ex: int total = 449;


int value1,value2 = 100;

Here the type can java primitive data type or name of a class or an interface.

Dynamic Initialization: Initializing a variable with the value that is computed during
the runtime.

Ex: double percentage = (sum/total) * 100 ;


Here the value of the variable percentage is assigned only after computing the right
hand side equation at runtime.

The Scope and lifetime of variables:


The scope of a variable is defined as the accessibility of a variable . The variables
have the block scope i.e. they are accessible from the line of their declaration to the
end the its block. The block is defined as the statements between the two curly braces
{ }.

Ex: VariableScope.java
Line 1 : class VariableScope{
2 public static void main(String args[]){
3 double height = 20;
4 if( height != 0){
5 double base = height / 2;
6 }
7 }
8 }

The scope of the variable height is from line no. 3 to 7.


The scope of the variable base is from line no. 5 to 6.

Lifetime of a variable: The lifetime of a variable is the interval of time for which the
variable exists; i.e. the time from when it is created to when it is destroyed

It is common to find confusion between scope and lifetime - though they are in cases
related, they are entirely different notions: lifetime is to do with a period of time during
the execution of a program, scope is to do with which parts of a program text. In Java,
lifetime is dynamic - you must execute the program (or do so in a thought experiment) in
order to determine it. Scope is static - determinable at compile time, or by reading the
program text.

Ex: VariableLifeTime.java
Line 1 : class VariableLifeTime{
2 public static void main(String args[]){
3 VariableLifeTime ob = new VariableLifeTime();
4 ob.calc();
5 }
6 public void calc(){
7 double height = 20;
8 if( height != 0){
9 double base = height / 2;
10 }
11 }
12 }
The lifetime of the variables height and base are only during the calc() method execution.

Arrays: An array is a container object that holds a fixed number of values of a single
type. The length of an array is established when the array is created. After creation, its
length is fixed.
Each item in an array is called an element, and each element is accessed by its numerical
index.

Note: Array indexes start with 0.

One dimensional array:-

Syntax:
type[] arrayName; ( type arrayName[]; is also valid )
arrayName = new type[size];
(or)
type[] arrayName = new type[size];

Ex: Save as ArrayDemo.java


class ArrayDemo {
public static void main(String[] args) {
int[] anArray; // declares an array of integers

anArray = new int[5]; // allocates memory for 10 integers

anArray[0] = 100; // initialize first element


anArray[1] = 200; // initialize second element
anArray[2] = 300; // etc.
anArray[3] = 400;
anArray[4] = 500;

System.out.println("Element at index 0: " + anArray[0]);


System.out.println("Element at index 1: " + anArray[1]);
System.out.println("Element at index 2: " + anArray[2]);
System.out.println("Element at index 3: " + anArray[3]);
System.out.println("Element at index 4: " + anArray[4]);
}
}
Multidimensional arrays:-A multidimensional array is an array whose components are
themselves arrays.

If we have the marks table of some students for three subjects.

sub1 sub2 sub3

Student1 10 20 30
Student2 30 40 50
Student3 50 60 70

And we need to calculate the sum of all three subjects of each student.
To do this we add row[0]col[0] +row[0]col[1]+row[0]col[2] . similarly for the
remaining row the addition should be done.
Syntax:-
type[][] arrayName; ( type arrayName[][]; is also valid )
arrayName = new type[rows][cols];

(or)
type[][] arrayName = new type[rows][cols];

1) int marksArray[][] = new int[3][3];

2) int array[][] = new int[3][];


array[0] = new int[3];
array[1]=new int[2];
array[2]=new int[4];

Ex: MultidimentionalArray.java
class MultidimentionalArray{
public static void main(String args[]){
int marksArray[][] = { {10,20,30 }, {30,40,50 }, {50,60,70} };
int sumArray[][] = new int[3][1];
for( int =0 ; i < 3; i++){
for (int j= 0;j<3;j++)

}
}
}
Operators in java:
Operators in java are classified as follows.
1) Arithmetic operators.
2) Relational operators.
3) Logical operators.
4) Assignment operators & Assignment arithmetic operators.
5) Increment & decrement operators.
6) Bitwise & shift operators
Arithmetic operators:
+ addition
- subtraction
* multiplication
/ division
% remainder or mod operator.

Relational Operators:
< less than
<= lesser than equal to
> greater than
>= greater than equal to
== equal to
!= not equal to

Logical Operators:
&& logical and
!! logical or
! not operator

Assignment Operators:
= assignment operator
Assigns the value on the right of = to the variable on the left

Assignment arithmetic operators:


+= (Ex: a+=2 is same as a= a+2)
-= (Ex: a-=2 is same as a= a-2)
*= (Ex: a*=2 is same as a= a*2)
/= (Ex: a/=2 is same as a= a/2)
%= (Ex: a%=2 is same as a= a%2)

Increment & Decrement operators:


++ pre/post increment operators
-- pre/post decrement operators

Ex:
int a = 2 ;
System.out.println( a++ ); // prints 3
a = 2;
System.out.println( ++a ); // prints 2
System.out.println( a ); // prints 3

Similarly decrement operators works by decreasing the value by 1.

Bitwise & shift Operators:


& bitwise AND
^ bitwise exclusive OR
| bitwise inclusive OR
~ Unary bitwise complement
<< Signed left shift
>> Signed right shift
>>> Unsigned right shift

Ex: Save as BitwiseANDDemo.java


class BitwiseANDDemo {
public static void main(String[] args) {
int bitmask = 0x000F;
int val = 0x2222;
System.out.println(val & bitmask); // prints "2"
}
}

Operator Precedence:
The operators in java have precedence over one other. The equations in java should be
calculated using the operator precedence. The below is the precedence table listed.

Operators Precedence
postfix expr++ expr--

++expr --expr +expr


unary -expr ~ !

multiplicative * / %

additive + -

shift << >> >>>

relational < > <= >= instanceof

equality == !=

bitwise AND &

bitwise exclusive ^
OR
bitwise inclusive |
OR
logical AND &&

logical OR ||

ternary ? :

= += -= *= /= %= &=
assignment ^= |= <<= >>= >>>=

Control Statements: Control flow statements, however, break up the flow of


execution by employing decision making, looping, and branching, enabling your program
to conditionally execute particular blocks of code.

The control statements can be classified into the following:


1) Selection statements
2) Iterative statements
3) Break or jump statements.
Selection statements: The selection statements will control the flow of execution based
on the condition evaluated to the Boolean value.
a) if
b) if else
c) else if ladder
d) switch
simple if: Simple if is a single selection statement. This statement executes the statements
in its block one time only if the given condition is true.
Ex: if(age<0){
System.out.println(“Age less than zero is invalid age”);
}
If the age = -1 then the statement “Age less than zero is invalid age” will be printed.

If else statement: This is a double selection statement.


Ex: if(age<0){
System.out.println(“Age less than zero is invalid age”);
}else{
System.out.println(“Valid age , accept application”);
}
If age = -1 then “Age less than zero is invalid age” will be printed else “Valid age ,
accept application” will be printed.

Else if ladder: This is a multiple selection statement.


Ex: if( day ==1){
System.out.println(“Monday”);
}else if( day == 2){
System.out.println(“Tuesday”);
}else if( day ==3){
System.out.println(“Wednesday”);
}else if( day ==4){
System.out.println(“Thursday”);
}else if( day ==5){
System.out.println(“Friday”);
}else if( day ==6){
System.out.println(“Saturday”);
}else{
System.out.println(“Sunday”);
}
If any one of the If condition is true executes the statements in that block and control
comes out without checking the other if statements.

Switch statement : This is also a multiple selection statement and works similar to the
else if ladder.
switch(day){

case 1: System.out.println(“Monday”);
break;
case 2: System.out.println(“Tuesday”);
break;
case 3: .
.
.
default: System.out.println(“Sunday”);
}
Every case statement should be ended by a break statement else the remaining statements
also will be executed.
Ex: if day = 2 , statements in case 2 will be executed and will also execute case 3, 4… if
break statement is missing after case 2.

Iterative statements: The iterative statements will control the flow of execution by
looping through the statements until the terminate condition is met.
a) for loop
b) while loop
c) do-while

The for statement : The statements within this loop will be iterated until the termination
condition is met
Syntax:
for (initialization; termination; increment) {
statement(s)
}
When using this version of the for statement,
• The initialization expression initializes the loop; it's executed once, as the
loop begins.
• When the termination expression evaluates to false, the loop terminates.
• The increment expression is invoked after each iteration through the loop;
it is perfectly acceptable for this expression to increment or decrement a
value.

Ex:
class ForDemo{
public static void main(String[] args){
int marks[] = { 20, 27, 24, 22, 21};
for(int i=0; i< marks.length ; i++){
System.out.println(“Marks “+ (i+1) + “ “ +marks[i]);
}
}
}

while loop: The while statement continually executes a block of statements while a
particular condition is true.
Syntax:
while (expression) {
statement(s)
}
The while statement evaluates expression, which must return a boolean value. If the
expression evaluates to true, the while statement executes the statement(s) in the while
block. The while statement continues testing the expression and executing its block until
the expression evaluates to false
Ex:
class WhileDemo{
public static void main(String[] args){
int marks[] = { 20, 27, 24, 22, 21};
int length = marks.length;
while(length>0){
System.out.println(“Marks “+ (i+1) + “ “ +marks[i]);
length-=1;
}
}
}

do- while statement: The Java programming language also provides a do-while
statement, which can be expressed as follows:
Syntax:
do {
statement(s)
} while (expression);

The difference between do-while and while is that do-while evaluates its expression at
the bottom of the loop instead of the top. Therefore, the statements within the do block
are always executed at least once
Ex:
class DoWhileDemo{
public static void main(String[] args){
int marks[] = { 20, 27, 24, 22, 21};
int length = marks.length;
do{
System.out.println(“Marks “+ (i+1) + “ “ +marks[i]);
length-=1;
} while(length>0);
}
}

Jump or breaking statements: The jump statements will control the flow of execution
by transferring the control from the current line to some other part of the program
a) break statement
b) continue statement
c) return statement

Ex: Save as BreakDemo.java


class BreakDemo {
public static void main(String[] args) {
double temperature = 10;
for (int i = 0; ; i++) {
if (temperature > 100)
break;
temperature+=6;
}
System.out.println("temperature " + temperature);
}
}

Ex: Save as ContinueDemo.java


class ContinueDemo {
public static void main(String[] args) {
double temperature = 10;
for (int i = 0; ; i++) {
temperature+=6;
if (temperature < 100)
continue;
}
System.out.println("temperature " + temperature);
}
}

Ex: Save as ReturnDemo.java


class ReturnDemo {
public static void main(String[] args) {
double temperature = 10;
double temp = checkTemperature(temperature);
System.out.println("temperature " + temp);
}

void checkTemperature(){
for (int i = 0; ; i++) {
if (temperature > 100)
return temperature;
temperature+=6;
}
return –1;
}

Type Conversion and casting: Java automatically converts one data type to another
type when both the types are compatible and destination type is larger than the source
type. This is called automatic type conversion.

Ex: int a=5;


long l = a; (long and int are compatible data types)
This is also called widening conersion.

The floating point and the integer types are compatible data types, where Boolean and
char are not.

The process of converting a one data type to another where the destination type is smaller
than the source type. This type of conversion is called narrowing conversion and cannot
be done automatically.

Ex: int a = 2;
short s = a;
Casting: Using explicit casting we can type convert the incompatible data types. This
explicit type conversion is called type casting.
Ex: float fVal = 3.5;
int a = (int)fVal;
System.out.println(a); // prints 3

When trying to type cast floating point numbers to integers, the decimal value gets
truncated and there will a loss of precision.

You might also like