2 Java
2 Java
Books
Books:
1. Naughton, Schildt, “The Complete Reference JAVA2”, TMH
Reference Books:
3. Brett Spell, Professional Java Programming, WROX Publication
Simple
Secure
Portable
Object-oriented
Robust (Doesn’t do memory crashing)
Multithreaded
Architecture-neutral
Interpreted
High performance
Distributed
Dynamic
Java Features
• Simple
Object oriented
Polymorphism
Inheritance
. multithreading
.
C++
Java
The Java Buzzwords (Definition)
• Secure: restricts the programmer to find the mistakes early, performs compile-
time (strong typing) and run-time (exception-handling) checks, manages
memory automatically.
• programs are confined to the Java execution environment and cannot access other
parts of the computer.
Java’s Features
• Secure
Internet
When java bytecode come from network or another machine, in that case before
executing that file verifier check first.
Java’s Features
• Pure Object Oriented
Class One
{
Public static void main(String arg[])
{
System.out.println(“Hello World”);
}
}
Java can open and access “objects” across the Net via URLs
(Uniform Resource Locator)----eg.
“http//:gamut.neiu.edu/~ylei/home.html”,
with the same ease as when accessing a local file system
#include<stdio.h>
Void main()
{
printf(“Value of I”,&i);
Ob1=ob2;
Ob1 Ob2
Memory
Java’s Features(continue)
• Robust
The single biggest difference between Java
and C/C++ is that Java has “a inner safe pointer-
model”, therefore it eliminates the possibility of
overwriting memory and corrupting data, so
programmers feel very safe in coding.
Computing platform include hardware and software
Platform
framework, this combination allows software to run.
Platform problem
Source code
Compiler
(windows)
Object code
Platform problem
Source code Source code Source code
Compiler
Interpreter
Phase I Phase II
Byte code
Byte code
Byte code
B=20
C=A+B
0 iload_1
Java 1 iload_2 Intermediate
Source code 2 iadd code
3 istore_3
Compiler
Interpreter
Phase I Phase II
mainly for c++ programmer
Why Java ?
• Portable
• Easy to learn
C Compilation process
Preprocessor
Compiler
Assembly code
Components of
Compiler
Assember
Libraries
Object code
Linker
Executable file
Preprocessor
/* this is demo */
#include<stdio.h>
void main()
{
printf (“hello”);
}
Preprocessor
push ebp
mov ebp, esp
and esp, -16
sub esp, 16
mov eax, OFFSET FLAT:.LC0
mov DWORD PTR [esp],
eax
Compiler generate assebmly code. call printf
leave
ret
Assembler
push ebp
mov ebp, esp
and esp, -16
sub esp, 16
mov eax, OFFSET FLAT:.LC0
mov DWORD PTR [esp],
eax
call printf
leave
ret Assembler
00101001100101001
10101111010100101
01010010101011010
01010101010010101
01001100111111100
10001010010101001
Assebler convert assemble code into object code. 01011111011111111
11111010000000011
10010010
Linker
001010011 001010011 001010011
001010011 001010011 001010011
010111101 010111101 010111101
010010101 Libraries
010010101 010010101
010010101 010010101 010010101
0110 0110 0110
Linker
Linker: Static linking one()
#include<stdio.h>
void main()
{ one(); } 01010
10000
Libraries 01010
01010
001010011001
010011010111
Call function
110
one()
Linker
Libraries
Object file1 Object file2
Linker
Size ?
JAVA Programming
Java Package
• Java package has two parts
– JDK( java development Kit)
– JRE(java runtime environment)
#include<iostream.h>
void main(int argc , char * argv[])
{
Cout<<“hello world “;
}
Java first program
• Java is pure object oriented programming
language.
Class demo
{
main funtion(arguments)
{
print statement for hello world
}
}
First Java Program
For including libraries in java(like include statement in c)
import java.lang.*;
Name of class
Class demo
{ Main method in java. With string type of argument
• The keyword void simply tells the compiler that main( ) does not
return a value. As you will see, methods may also return values.
A Closer Look at the First Sample Program
• Any information that you need to pass to a method is received by variables
specified within the set of parentheses that follow the name of the method.
These variables are called parameters. If there are no parameters required
for a given method, you still need to include the empty parentheses.
• System is a predefined class that provides access to the system, and out is
the output stream that is connected to the console.
Commands to run
• Save file with name of class, which contains
main method
• javac demo.java
• java demo
Creating, Compiling And Running Java
Programs
Java program Type it in with the text editor of your choice
filename.java
(java file)
Java compiler
javac
Java byte code
filename.class
To compile the program at the
command line type "javac
filename.java"
Java Interpreter
java
To run the interpreter, at the
command line type "java
filename"
Compiling The Smallest Java Program
Smallest.java
public class Smallest
Type “javac
{ Smallest.java”
public static void main (String[] args)
{
}
}
javac
Smallest.class
(Java byte code)
10000100000001000
00100100000001001
: :
Running The Smallest Java Program
Smallest.class
(Java byte code)
10000100000001000
00100100000001001
: :
java
*/
} // end of main
} // end of class
Compiling and Running
In order to run a Java program:
• First you compile it
– that is, you run a program called compiler that checks whether the
program follows the Java syntax
– if it finds errors, it lists them
– If there are no errors, it translates the program into Java bytecode
– Example: assume you created a program called Hello.java
prompt>javac Hello.java
– If successful, this creates a file Hello.class which contains the
translation (Java bytecode) of Hello.java
When learning a new language, the first program people usually write is
one that salutes the world :). Here is the Hello world program in Java.
/*
This program prints out “hello world!” and terminates.
*/
public class Hello {
public static void main (String args[]) {
System.out.println(“Hello world!”);
} // end of main
} // end of class
Notes
• Comments
– what follows after // on the same line is considered comment
– Or, what is in between /* this is a comment */
• Indentation
– is for the convenience of the reader; compiler ignores all spaces and new lines ; the
delimiter for the compiler is the semicolon
System.out.println(variable-name);
prints the value of variable <variable-name> to the user
} // end of main
} // end of class
Example:
int a, b, c;
double x;
int sum;
Example
/*
Printing ages.
*/
public class MyFirstJavaProgram {
public static void main (String args[]) {
myAge = 20;
myFriendAge = myAge + 1; //one year older
System.out.println(“Hello, I am “ +myAge + “years old, and my friend is “ +
myFriendAge + “ years old”);
System.out.println(“Goodbye”);
} // end of main
} // end of class
Java Data Type
Type Description
byte 8 bit signed integer
• /* multiple line
Comment
*/
expression_1 + expression_2
• int i=5;
• System.out.print(“i = ” + i--);//print 5, then i becomes 4
• System.out.print(“i = ” + --i);//subtract 1 from i, then print 3
Relational Operator
• a < b a less than b. (true/false)
• a <= b a less than or equal b. (true/false)
• a > b a greater than b. (true/false)
• a >= b a greater than or equal to b. (true/false)
• These operations always return a boolean value.
• System.out.println(“23 is less than 65 ” +23<65); // true
• System.out.println(“5 is greater than or equal to 25.00?” +
5>=25.00); // false
Equality Operator
• a==b a equal to b. (true/false)
• a!=b a not equal to b. (true/false)
}
}
> java Example
f && f false
f && t false
t && f false
t && t true
>
Logical (||) Operator Examples
boolean t = true;
boolean f = false;
}
}
> java Example
f || f false
f || t true
t || f true
t || t true
>
Logical (!) Operator Examples
}
}
a 00000000000000000000000000001010 10
& b 00000000000000000000000000001100 12
AND a & b 00000000000000000000000000001000 8
| a
b
00000000000000000000000000001010
00000000000000000000000000001100
10
12
OR a | b 00000000000000000000000000001110 14
^ a
b
00000000000000000000000000001010
00000000000000000000000000001100
10
12
XOR a ^ b 00000000000000000000000000000110 6
~ a
~a
00000000000000000000000000001010
11111111111111111111111111110101
10
-11
NOT
Shift Operators (Bit Level)
<< >> >>>
a 00000000000000000000000000000011 3
a << 2 00000000000000000000000000001100 12
<<
Left b 11111111111111111111111111111100 -4
b << 2 11111111111111111111111111110000 -16
a 00000000000000000000000000000011 3
a >> 2 00000000000000000000000000000000 0
>>
Right b 11111111111111111111111111111100 -4
b >> 2 11111111111111111111111111111111 -1
Shift Operator >>>
int a = 3; // ...00000011 = 3
int b = -4; // ...11111100 = -4
a 00000000000000000000000000000011 3
Right 0 b 11111111111111111111111111111100 -4
b >>> 2 00111111111111111111111111111111 +big
Shift Operator Examples
public class Example {
public static void main(String[] args) {
int a = 3; // ...00000011 = 3
int b = -4; // ...11111100 = -4
a 00000011 3
a >>> 2 00000000000000000000000000000000 0
c = (byte) 00000000 0
>>>
Right b 11111100 -4
Fill 0 b >>> 2 00111111111111111111111111111111 1073741823
c = (byte) Much to big for byte 11111111 -1
Algorithm
• An algorithm is a set of steps (rules) for solving a problem
in terms of:
actions to be executed
the order of actions execution
• We are using programming languages to specify the steps in
an algorithm
actions are called statements
the order of statement execution is called program
control
Flow of Control
• The order of statement execution in a program or method is
called the flow of control
• Some programming statements modify that order, allowing
us to:
• decide whether or not to execute a particular statement, or
• repeat a statement execution over and over
False True
Condition?
Representation of Constructs
• Iteration: Repeat some steps.
Step 1
Step2
False
Condition
True
Control Statements
Control Statements
• Single Selection
the if statement
• Double Selection
the if/else statement
nested if
• Multiple Selection
if-else -if ladder
the switch statement
Single Selection Statement
if ( booleanExpr )
statement; condition
• Example
– It is raining outside. Take your umbrella.
• Flowchart
false
Single Selection Statement
if ( countNumbers == 10 ) System.out.println( );
if ( grade >= 90 )
System.out.println( “You are an excellent student!” );
if ( dayOfTheWeeek > 5 )
{
System.out.println( “Time to relax…” );
compound statement
System.out.println( “Weekend.”);
}
false true
Have coffee Hungry? Have lunch
Double Selection Statement
if ( dayOfTheWeek > 5 )
{
System.out.println( “Weekend.”);
System.out.println( “Time to relax…” );
}
else
{
System.out.println( “Workday.”);
System.out.println( “Go to work!” );
}
SCHOOL OF ENGINEERING & TECHNOLOGY
D E PA R T M E N T O F C O M P U T E R S C I E N C E A N D E N G I N E E R I N G
if( booleanExpr1 )
statement1;
else if ( booleanExpr2 ) condition
statement2;
else if ( booleanExpr3 )
statement3;
•
•
•
else
statement;
Multiple Selection Statement
switch( booleanExpr)
{ condition
case value1:
statement1;
break;
case value2:
statement2;
break;
•
•
•
case value N;
statementN;
break;
default:
statement;
}
Switch Statement Execution
while statement
for statement
do-while statement
while statement
while (Boolean Expression)
{
//body of loop (sequence of statements)
}
// summation from 1 to N
Order of Execution i=1; s=0;
(1) while (i <= N)
{
s = s + i;
while (< Cond. Expr. >) ++i;
}
False (4)
for Statement
3 True 4
6 < Statement
>
False
for Statement variations
• break statement
• continue statement
• return statement
break Statement
• To exit a single loop
While (BooleanExpr)
{
If(condition)
Break;
}
arr[0]
arr[1]