Unit I Introduction
Unit I 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.
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.
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.
Dynamic: Java can verify and resolve objects at runtime and updates the bytecode
dynamically. This is one feature of called applet programming.
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.
Save as “HelloWorld.java”
class Helloworld
{
public static void main(String args[]){
System.out.println(“Hello World”);
}
}
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
Variables: The unit of storage which can modify its data anytime during the
execution of the program are called variables.
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: 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 }
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.
Syntax:
type[] arrayName; ( type arrayName[]; is also valid )
arrayName = new type[size];
(or)
type[] arrayName = new type[size];
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];
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
Ex:
int a = 2 ;
System.out.println( a++ ); // prints 3
a = 2;
System.out.println( ++a ); // prints 2
System.out.println( a ); // prints 3
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--
multiplicative * / %
additive + -
equality == !=
bitwise exclusive ^
OR
bitwise inclusive |
OR
logical AND &&
logical OR ||
ternary ? :
= += -= *= /= %= &=
assignment ^= |= <<= >>= >>>=
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
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.
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.