one day java workshop by:pankaj chejara. c compilation process preprocessor compiler assember linker...
TRANSCRIPT
One Day Java WorkShop
By:Pankaj Chejara
C Compilation process
Preprocessor
Compiler
Assember
Linker
Components of Compiler
Assembly code
Object code Libraries
Source code( .c file)
Executable file
Preprocessor
Preprocessor
/* this is demo */#include<stdio.h>void main(){ printf (“hello”);}
code of stdio.h filevoid main(){ printf (“hello”);}Preprocessor remove comments and include
header files in source code, replace macro name with code.
Compiler
Compiler
code of stdio.h filevoid main(){ printf (“hello”);}
push ebpmov ebp, espand esp, -16sub esp, 16mov eax, OFFSET FLAT:.LC0mov DWORD PTR [esp], eaxcall printfleaveret
Compiler generate assebmly code.
Assembler
Assembler
Assebler convert assemble code into object code.
push ebpmov ebp, espand esp, -16sub esp, 16mov eax, OFFSET FLAT:.LC0mov DWORD PTR [esp], eaxcall printfleaveret
001010011001010011010111101010010101010010101011010010101010100101010100110011111110010001010010101001010111110111111111111101000000001110010010
Linker
Linker
0010100110010100110101111010100101010100101010110
0010100110010100110101111010100101010100101010110
0010100110010100110101111010100101010100101010110
Libraries
Platform problem
Source code
Compiler(windows)
Object code
Platform problem
Source code
Compiler(windows)
Object code
Compiler(linux)
Compiler(mac)
Source code Source code
Object code
Object code
java
JavaSource code
Compiler
Intermediate code
Phase I
Intermediate code
Interpreter
Object code
execution
Phase II
Byte code
Interpreter(windows)
Object code
Interpreter(linux)
Interpreter(mac)
Byte code
Object code
Object code
Java Features Simple Pure object oriented Platform independent Strongly typed Garbage collection Secure
Java Package Java package has two parts
JDK( java development Kit) JRE(java runtime environment)
Java version 1.7
Hello program in c++
#include<conio.h>void main(){cout>>hello world ;}
1. For including header files.
2. main function start
3. print on screen hello world
#include<conio.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 import java.lang.*; class demo { public static void main(String arg[]) { System.out.println(“Hello World”); } }
For including libraries in java(like include statement in c)
Name of class
To print message on screen(like printf function)
Main method in java. With string type of argument
Commands to run Save file with name of class, which contains
main method javac demo.java
java demo
Java data types
Type Description
byte 8 bit signed integer
short 16 bit signed integer
int 32 bit signed integer
long 64 bit signed integer
float 32 bit signed real number
double 64 bit signed real number
char 16 bit Unicode character (ASCII and beyond)
boolean 1 bit true or false value
String A sequence of characters between double quotes ("")
Practice Write a program in which declare variable of
each data type. Assign value to those variable. How to print those value.
Acceptable Implicit Casts
char16 bit
double64 bit
float32 bit
long64 bit
int32 bit
short16 bit
byte8 bit
Illegal b = l;l = f;c = s;
OKl = b;i = c;f = l
char16 bit
double64 bit
float32 bit
long64 bit
int32 bit
short16 bit
byte8 bit
char16 bit
double64 bit
float32 bit
long64 bit
int32 bit
short16 bit
byte8 bit
Automatic Promotion with Arithmetic
Illegal Castss = s + b;s = s + s;
OKs = (short)(s + b);s = (short)(s + s);
Arithmetic is never donein 8 or 16 bit containers.
char16 bit
double64 bit
float32 bit
long64 bit
int32 bit
short16 bit
byte8 bit
Arithmetic Promotion with Mixed Primitives
Illegal Castsi = i + l;f = f + d;l = l + f;
OKi = (int)(i + l);d = (double)(f + d);l = (long)(l + f);
Arithmetic is donein the "widest" type.
String (+) OperatorString Concatenation
System.out.println(“value is"+ i);
value is 10
int i=10;
String (+) OperatorString Concatenation
"Now is " + "the time."
"Now is the time."
String (+) OperatorAutomatic Conversion to a String
If either expression_1If either expression_1 or expression_2 evaluatesto a string the other will be converted to a string if needed. The result will be their concatenation.
expression_1 + expression_2
String (+) OperatorAutomatic Conversion with Primitives
"The number is " + 4
"The number is " + "4"
"The number is 4"
Practise Declare a variable in java (don’t initiase it )
and try to compile your program.
Practise Write a program in which declare two integer
variable assign value 10 and 12 and perform bitwise and, or, xor, not operator on them.
int a=10;int b=12;int c=a&b;Int d=a|b;Int e=a^b;Int f=~a;
Logical Operators (Bit Level) & | ^ ~
int a = 10; // 00001010 = 10int b = 12; // 00001100 = 12
a 00000000000000000000000000001010 10b 00000000000000000000000000001100 12a & b 00000000000000000000000000001000 8
a 00000000000000000000000000001010 10b 00000000000000000000000000001100 12a | b 00000000000000000000000000001110 14
a 00000000000000000000000000001010 10b 00000000000000000000000000001100 12a ^ b 00000000000000000000000000000110 6
a 00000000000000000000000000001010 10~a 11111111111111111111111111110101 -11
&AND
|OR
^XOR
~NOT
Practise Write a program in which declare two integer
variable assign value 3 and -4 and perform shift operator.
int a=3;int b=-4;int c=a<<2;Int d=b<<2;Int d=a>>2;Int f=b>>2;
Shift Operators (Bit Level) << >> >>>
• Shift Left << Fill with Zeros
• Shift Right >> Based on Sign
• Shift Right >>> Fill with Zeros
Shift Operators << >>int a = 3; // ...00000011 = 3int b = -4; // ...11111100 = -4
a 00000000000000000000000000000011 3a << 2 00000000000000000000000000001100 12
b 11111111111111111111111111111100 -4b << 2 11111111111111111111111111110000 -16
<<Left
>>Right
a 00000000000000000000000000000011 3a >> 2 00000000000000000000000000000000 0
b 11111111111111111111111111111100 -4b >> 2 11111111111111111111111111111111 -1
Shift Operator >>> int a = 3; // ...00000011 = 3int b = -4; // ...11111100 = -4
>>>Right 0
a 00000000000000000000000000000011 3a >>> 2 00000000000000000000000000000000 0
b 11111111111111111111111111111100 -4b >>> 2 00111111111111111111111111111111 +big
Shift Operator Examplespublic class Example {public static void main(String[] args) {
int a = 3; // ...00000011 = 3int b = -4; // ...11111100 = -4
System.out.println("a<<2 = " + (a<<2));
System.out.println("b<<2 = " + (b<<2));
System.out.println("a>>2 = " + (a>>2));
System.out.println("b>>2 = " + (b>>2));
System.out.println("a>>>2 = " + (a>>>2));
System.out.println("b>>>2 = " + (b>>>2));}
}
> java Example a<<2 = 12 b<<2 = -16 a>>2 = 0 b>>2 = -1 a>>>2 = 0 b>>>2 = 1073741823 >
Shift Operator >>> and Automatic Arithmetic Promotion
byte a = 3; // 00000011 = 3byte b = -4; // 11111100 = -4byte c;c = (byte) a >>> 2c = (byte) b >>> 2
>>>RightFill 0
a 00000011 3a >>> 2 00000000000000000000000000000000 0c = (byte) 00000000 0
b 11111100 -4b >>> 2 00111111111111111111111111111111 1073741823c = (byte) Much to big for byte 11111111 -1
Shift Operators << >>int a = 3; // ...00000011 = 3int b = -4; // ...11111100 = -4
a 00000000000000000000000000000011 3a << 2 00000000000000000000000000001100 12
b 11111111111111111111111111111100 -4b << 2 11111111111111111111111111110000 -16
<<Left
>>Right
a 00000000000000000000000000000011 3a >> 2 00000000000000000000000000000000 0
b 11111111111111111111111111111100 -4b >> 2 11111111111111111111111111111111 -1
Shift Operator >>> int a = 3; // ...00000011 = 3int b = -4; // ...11111100 = -4
>>>Right 0
a 00000000000000000000000000000011 3a >>> 2 00000000000000000000000000000000 0
b 11111111111111111111111111111100 -4b >>> 2 00111111111111111111111111111111 +big
Shift Operator Examples
public class Example {public static void main(String[] args) {
int a = 3; // ...00000011 = 3int b = -4; // ...11111100 = -4
System.out.println("a<<2 = " + (a<<2));
System.out.println("b<<2 = " + (b<<2));
System.out.println("a>>2 = " + (a>>2));
System.out.println("b>>2 = " + (b>>2));
System.out.println("a>>>2 = " + (a>>>2));
System.out.println("b>>>2 = " + (b>>>2));}
}
> java Example a<<2 = 12 b<<2 = -16 a>>2 = 0 b>>2 = -1 a>>>2 = 0 b>>>2 = 1073741823 >
Practise Write a program and test output of following int a= 10%3; int b=-10%3; int c=10%-3; int d=-10%-3;
Control Statement If-else switch continue break
Write a program to check a number is odd or even.
Classes in java
Class demo{ int first; int second;void printvalue() { System.out.println(“first:”+first); System.out.println(“Second:”+second); }}Class myclass{ public static void main(String arg[]) { demo d=new demo(); d.printvalue(); }}
}
Instance variable: Associated with instance
}Method
Creating object of class demo:demo d;d=new demo();
Practise Create a class with three variables of boolean,
int and float data types. Don’t write any constructor in this class. Write a function which print values of these
variables.
Practise Create a class with
constructor( parameterized and non- parameterized).
Also create a function with same name as name of class.
Inheritance
How to inherit?
class one{ one() { System.out.println(“Class One”); }}Class two extends one{ two(){System.out.println(“Class two”);}}
class A {int i; // public by defaultprivate int j; // private to Avoid setij(int x, int y) {i = x;j = y;}}// A's j is not accessible here.class B extends A {int total;void sum() {total = i + j; // ERROR, j is not accessible here}}
Accessbility
Practise Create a class box which have three variables
width, height, depth of float data type. Write constructor box(float, float, float) Write one more constructor box() Write a method to calculate volume
(height*width*depth) What if we want to add weight attribute to
class?
Super Create a class with variable I Initialise this value in constructor by 10 Now inherit this class in child class In child class create one more variable I
How we can access parent class variable I;
This keyword class demo { int a; Float b; demo(int a, float b) { a=a; b=b; }
}
Final keyword Create a class with final keyword, and now try
to inherit this class in another class Create a variable with final keyword and now
try to change it’s value Create a method with final keyword in a class ,
now inherit this class and try to override this method in child class.
Abstract class
abstract class ab{ int a,b; void print() { System.out.println(“a:”+a); System.out.println(“b”+b);}
abstract int add(int x, int y);}
ab object1=new ab();X
Practise Create a abstract class and try to make object
of this class.
Abstract class
class myclass extends ab{Int c;}
myclass object1=new myclass(); X
Abstract class
class myclass extends ab{ int c; void printc(){System.out.println(“C:”+c);} int add(int x,int y){ return x+y;} }
myclass object1=new myclass();
Interface Interface have only method declaration. Have only constant variable.
interface myinterface{void add();void subtract();void multiply }
Interface In interface every variable must be initialised. every method have only declaration. No method have definition.
How to use interface?interface myinterface{ int i=0; void mydemo(); void printvalue();}
class my implements myinterface { void mydemo() { } void printvalue() { } }
class inter{ public static void main(String arg[]) { my m=new my(); }}
Practise Create a interface and implement in class don’t define any method of interface in class now create a object of your class.
Exception Handling
Why Exception handling?
Exception
class one{ public static void main(String arg[]) { System.out.println(“Before exception”); throw new ArithmeticException(); }}
Exception
class one{ public static void main(String arg[]) { System.out.println(“Before exception”); int b=0; try { b=4/0;} catch(ArithmeticException e) { System.out.println(“After Exception”); System.out.println(“ value of b:”+b); } }}
Exception Try Catch Throw Throws Finally
How to display info of exception?
class one{ public static void main(String arg[]) { System.out.println(“Before exception”); int b=0; try { b=4/0;} catch(ArithmeticExceptin e) { System.out.println(“Exception =“+e); System.out.println(“After Exception”); System.out.println(“ value of b:”+b); } }}
Nested try catch
Manually throw exception
Throw new ArithmeticException();
Throw new ArithmeticException(“Myexception”);
Throw new <type of exception>();
Practise Write a program in which manually throw
exception
class one{ public static void main(String arg[]) { throw new ArithmeticException(); }}
Practise Try to run following example
class one{ public static void main(String arg[]) { throw new illegalAccessException(); }}
Exception hierarchy
Throwable
Exception Error
Run time ExceptionArithmeticException
IllegalAccessException
Practise How to run this program
class one{ public static void main(String arg[]) { throw new illegalAccessException(); }}
class one{ public static void main(String arg[]) { try{ throw new illegalAccessException(); } catch(IllegalAccessException e) {System.out.println(e);}} }
Other Solution
Tell others that your code can throw exception.
class one{ public static void main(String arg[]) throws IllegalAccessException { try{ throw new IllegalAccessException(); } catch(IllegalAccessException e) {System.out.println(e);}} }
Throws Used to tell other programmer that code can
throw exception so provide exception handling.
Practise
What if we want some piece of code to be executed in any condition.
Options If written in try block(if exception occurred
then control transferred to catch) If written in catch block(what if exception not
occurred in that case catch block will not execute.
Q What is differene between throw and throws? Can we write try without catch?
Finally block With try catch block write one finally block Finally block will always execute.
Input/Output in java
Input/Output
Java Program
Handling input/output for files, socket and devices are same.
Streams Unidirectional
Java Program destination
Output Stream: Data from program to destination
Input/Output
Java Program
Destination/Source
Output Stream: Data from program to destination
InputStream: Data from source to program
Stream types: Binary Stream
Java Program
Binary StreamFor dealing with binary information.
1
Stream types: Character Stream
Java Program
Character StreamFor dealing with information in character form.
2
Streams
Reading from file1. Open a input stream for file2. Read information sequentially from stream
until there is information.3. After reading information close stream.
Writing to file1. Open a Output stream for file2. Write information sequentially from stream
until there is information.3. After writing information close stream.
Byte Streams InputStream and OutputStream
Abstract classes
Character Streams Reader and Writer streams
Abstract classes Define methods common to all character streams
These methods correspond to InputStream/OutputStream methods
Example: Read method of InputStream returns lowest 8 bits of an int
as a byte Read method of Reader returns lowest 16 bits of an int as a
char
How to open stream?
FileInputStream fs=new FileInputStream(<filename>);
FileInputStream fs=new FileInputStream(“one.txt”);
Method: read()read method return one byte at a time in form of integer
Simple program to read from file
1. import java.io.*;2. class fileio3. {4. public static void main(String arg[])5. {6. int i=0;7. try8. {9. FileInputStream fs=new FileInputStream("one.txt");10. while((i=fs.read())!=-1)11. {12. System.out.print((char)i);13. }14. }15. catch(Exception e){System.out.println(e);}16. }17. }
Importing input/output library
Opening a file stream can throw an exception. To handle that exception we need
try-catch.
Opening a stream to file. This is byte stream so information handled in byte format.
Read until EOF of file.
Type casting in character.
Simple program to write
1. import java.io.*;2. class fileio3. {4. public static void main(String arg[])5. {6. int i=0;7. try8. {9. FileInputStream fs=new FileInputStream("one.txt");10. while(++i<10)11. { 12. fs.write(65);13. }14. }15. catch(Exception e){System.out.println(e);}16. }17. }
Predefined Streams Java has predefined byte streams:
System.in System.out System.err
Taking input from keyboard
import java.io.*;class rdata{ public static void main(String arg[]) throws IOException { int s;
while((s=System.in.read())!='\n') System.out.print((char)s);
}
}
s=System.in.read();while(s!=‘\n’) { System.out.println((char)s); s=System.in.read(); }
Efficiency of program Input taken byte by byte ( One byte at a time) Program is not efficient because it will take
more time processing of one byte at a time.
Solution: Use buffer to store byte temporarily and then
transfer to program.
FileInputStream
Java Program
FileInutStreamOne byte at a time.
00101011
BufferedStream on FileInputStream
Java Program
FileInputStreamBufferedInputStrea
m
FileInputStream fs=new FileInputStream(“one.txt”);BufferedStream bs=new BufferedStream(fs);
Or
BufferedStream bs=new BufferedStream(new FileInputStream(“one.txt”));
00101011001010110010101100101011
First input program
JavaProgra
m
System.inIt is a byte stream.
InputStreamReader covert byte stream into character stream.
BufferedReader provide buffer for better efficiency.
InputStreamReader ins=new InputStreamReader(System.in);BufferedReader br=new BufferedReader(ins);
String s=br.readLine();
Program to take input from user
1. import java.io.*;2. class fileio3. {4. public static void main(String arg[])5. {6. int i=0;7. try8. { InputStreamReader ins=new
InputStreamReader(System.in);9. BufferedReader br=new BufferedReader(ins);10. String s=br.readLine();11. System.out.println(“Input given by user”+s);12. 13. 14. }15. catch(Exception e){System.out.println(e);}16. }17. }
How to write primitive data directly?
1. import java.io.*;2. class fileio3. {4. public static void main(String arg[])5. {6. int i=0;7. try8. { FileOutputStream fos=new FileOutputStream(“one.txt”);9. DataOutputStream dos br=new DataOutputStream(fos);10. dos.writeFloat(12.3f);11. dos.writeDouble(20.5);12. 13. 14. }15. catch(Exception e){System.out.println(e);}16. }17. }
Why so much classes ?
Primitive data type
How to write primitive data directly?
1. import java.io.*;2. class fileio3. {4. public static void main(String arg[])5. {6. int i=0;7. try8. { FileInputStream fis=new FileInputStream(“one.txt”);9. DataInputStream dos br=new DataInputStream(fos);10. dos.readFloat(12.3f);11. dos.readDouble(20.5);12. 13. 14. }15. catch(Exception e){System.out.println(e);}16. }17. }
Multithreading
104
How to create thread? Two techniques to create threads in java 1) implementing the Runnable interface
The Runnable interface should be implemented by any class whose instances are intended to be executed by a thread. The class must define a method, called run, with no arguments.
invoke Thread constructor with an instance of this Runnable class
2) extending Thread Define a subclass of java.lang.Thread
Define a run method In another thread (e.g., the main), create an
instance of the Thread subclass Then, call start method of that instance
Simple loop program
class thr{ public static void main(String arg[]) { int i,j; //First loop for(i=0;i<10;i++) System.out.println(“First loop”+i);
//Second loop for(j=0;j<10;j++) System.out.println(“Second loop”+j); }}
Create thread Implement Runnable interface in your class Provide definition of run() method in your
class Put code which you want to run parallel in run
method In main method create object of your class Create object of thread class, in constructor
pass object of your class Call start() method
Create threadclass first implements Runnable{ public void run() { for(int i=0;i<10;i++)
System.out.println("First thread"+i); }}
class second implements Runnable { public void run() { for(int j=0;j<10;j++)
System.out.println("Second thread"+j); } }
Step1: class implements Runnable interface
Step2:provide definition of run method
Step3:Put code which you want to run parallel
Create threadclass thred { public static void main(String arg[]) {
first f=new first(); Thread th1=new Thread(f); th1.start();}
}
Step4:Create object of class first
Step5:Create object of Thread
Step6:Start thread by calling start method.
Multithreading server 1. Create server (using ServerSocket class) 2. Start listening (calling accept method) 3. When a client request received, create a
new thread and in that thread pass socket object.
4.Put all these three steps in a infinite loop.
Multithreading server
While(true) {ServerSocket ss=new ServerSocket(9999);Socket so= ss.accept();
ClientHandler ch=new ClientHandler(so);Thread th=new Thread(ch);th.start();}
How to create thread Extends Thread class in your class Override run method In main method create object of your class call start methods
Create threadclass first extends Thread{ public void run() { for(int i=0;i<10;i++)
System.out.println("First thread"+i); }}
Step1: class extends Thread class
Step2:provide definition of run method
Step3:Put code which you want to run parallel
Create threadclass thred { public static void main(String arg[]) {
first f=new first(); th1.start();}
}
Step4:Create object of class first
Step6:Start thread by calling start method.