SlideShare a Scribd company logo
<Codemithra />
Java & Python | Parallel Course
Programming Paradigms
Functional/procedural programming:
Program is a list of instructions to the computer
Object-oriented programming
Program is composed of a collection objects that communicate with each other
Java Compilation
Python
Source
Code
Compiler Byte Code Interpreter Processor
First Program
print("Hello, World!")
class Main {
public static void main(String args[]){
System.out.println("Hello, World!");
}
}
a = 10
b = 10.4
c = "String"
d = 'single quoted string'
e = True
print("a, b, c, d, e", a, b, c, d, e)
class Main {
public static void main(String[] args) {
int a = 10;
float b = 10.4f;
String c = "String";
// Not possible
// String d = 'String';
boolean e = true;
System.out.println("a, b, c, e " + a + " " + b + " " + c + " " + e);
}
}
Variables
Numbers in Python
a = 10
print(a, type(a))
a = float(a)
print(a, type(a))
a = complex(a)
print(a, type(a))
a = complex(a, a)
print(a, type(a))
Numbers in Java
class Main {
public static void main(String[] args) {
Integer a = 10;
Float b = 10.4f;
Double c = 10.4d;
System.out.println("a, b, c " + a + " " + b + " " + c);
}
}
Number methods
print("math.floor " , math.floor(81.5));
print("math.ceil " , math.ceil(81.5));
print("math.round " , math.round(81.5));
print("math.exp " , math.exp(3));
class Main {
public static void main(String[] args) {
System.out.println("Math.floor " + Math.floor(81.5));
System.out.println("Math.ceil " + Math.ceil(81.5));
System.out.println("Math.round " + Math.round(81.5));
System.out.println("Math.exp " + Math.exp(3));
}
}
Number methods
print("math.abs " , math.abs(-6));
print("math.sqrt " , math.sqrt(81));
print("Integer.max " , max(5, 6));
print("Integer.min" , min(5, 6));
class Main {
public static void main(String[] args) {
System.out.println("Math.abs " + Math.abs(-6));
System.out.println("Math.sqrt " + Math.sqrt(81));
System.out.println("Integer.max " + Integer.max(5, 6));
System.out.println("Integer.min" + Integer.min(5, 6));
}
}
String methods
str = "ethnus"
print(str.endswith("nus"))
print(str.startswith("eth"))
print(str.isdigit())
print(str.isspace())
class Main {
public static void main(String[] args) {
String str = "ethnus tech";
Character c = '3';
System.out.println(str.endsWith("nus"));
System.out.println(str.startsWith("eth"));
System.out.println(Character.isDigit(c));
System.out.println(Character.isSpace(c));
}
}
String methods
str = "ethnus"
print(str.upper())
print(str.lower())
class Main {
public static void main(String[] args) {
String str = "ethnus tech";
System.out.println(str.toUpperCase());
System.out.println(str.toLowerCase());
}
}
Arithmetic Operators
print(a + b) System.out.println(a + b) 110
print(a - b) System.out.println(a - b) 90
print(a / b) System.out.println((float) a / b) 10.0
print(a * b) System.out.println(a * b) 1000
print(a ** b) System.out.println(Math.pow(a, b)) 100000000000000000000
print(a // b) System.out.println(a / b) 10
print(a % b) System.out.println(a % b) 0
a = 100, b = 10
Comparison Operators
print(a == b) System.out.print(a == b) False
print(a > b) System.out.print(a > b) True
print(a >= b) System.out.print(a >= b) True
print(a < b) System.out.print(a < b) False
print(a <= b) System.out.print(a <= b) False
print(a != b) System.out.print(a != b) True
print(a == b) System.out.print(a == b) False
a = 100, b = 10
Bitwise Operators
print(a & b) System.out.print(a & b) 0
print(a | b) System.out.print(a | b) 6
print(a << 1) System.out.print(a << 1) 4
print(a >> 1) System.out.print(a >> 1) 1
print(a ^ b) System.out.print(a ^ b) 6
a = 2, b = 4
Logical Operators
print(a and b) System.out.print(a && b) False
print(a or b) System.out.print(a || b) True
print(not a) System.out.print(!a) False
a = True, b = False
Ternary Operator
a = 100
b = 10
min = a < b and a or b
print(min)
class Main {
public static void main(String[] args) {
int a = 100;
int b = 10;
int min = a < b ? a : b;
System.out.println(min);
}
}
Branching
a = ''
if a:
print("Value of a = ", a)
else:
print("False value in a")
a = 0
if a:
print("Value of a = ", a)
else:
print("False value in a")
a = -1
if a:
print("Value of a = ", a)
else:
print("False value in a")
a = False
if a:
print("Value of a = ", a)
else:
print("False value in a")
Branching
class Main {
public static void main(String[] args) {
boolean a = true;
if(a)
System.out.println("A is true");
else
System.out.println("A is false");
}
}
class Main {
public static void main(String[] args) {
int a = 5;
if(a)
System.out.println("A is true");
else
System.out.println("A is false");
}
}
Branching
a = 5
if a:
print("a is not False")
if a > 3:
print("a is greater than 3")
else:
print("a is lesser than or equal to 3")
class Main {
public static void main(String[] args) {
int a = 5;
if(a > 0) {
if(a > 3) {
System.out.println("a is greater than 3");
} else {
System.out.println("a is greater than 3");
}
}
}
}
Branching
public class Main {
public static void main(String[] args) {
char grade = 'B';
switch(grade) {
case 'A' :
System.out.println("Excellent!");
break;
case 'B' :
case 'C' :
System.out.println("Well done");
break;
case 'D' :
System.out.println("You passed");
break;
default :
System.out.println("Invalid grade");
}
System.out.println("Your grade is " + grade);
}
}
Looping
count = 0
while (count < 9):
print(count)
count = count + 1
class Main {
public static void main(String[] args) {
int count = 0;
while (count < 9) {
System.out.println(count);
count = count + 1;
}
}
}
Looping
count = 0
while (count < 9):
if count == 4:
count = count + 1
continue
print(count)
count = count + 1
class Main {
public static void main(String[] args) {
int count = 0;
while (count < 9) {
if(count == 4) {
count = count + 1;
continue;
}
System.out.println(count);
count = count + 1;
}
}
}
Looping
count = 0
for count in range(0,9):
if count == 4:
continue
print(count)
class Main {
public static void main(String[] args) {
int count;
for(count = 0; count < 9; count++) {
if (count == 4)
continue;
System.out.println(count);
}
}
}
count = 0
for count in range(0,9):
if count == 4:
break
print(count)
class Main {
public static void main(String[] args) {
int count;
for(count = 0; count < 9; count++) {
if (count == 4)
break;
System.out.println(count);
}
}
}
Looping
count = 0
for count in range(0,9):
if count == 4:
continue
else:
print(count)
class Main {
public static void main(String[] args) {
int count;
for(count = 0; count < 9; count++) {
if (count == 4)
continue;
else
System.out.println(count);
}
}
}
count = 0
for count in range(0,9):
if count == 4:
pass
print(count)
class Main {
public static void main(String[] args) {
int count;
for(count = 0; count < 9; count++) {
if (count == 4) {
}
System.out.println(count);
}
}
}
Looping
x = 10
while True:
print(x)
x = x + 1
if x > 19:
break
public class Main {
public static void main(String[] args) {
int x = 10;
do {
System.out.print(x + "t");
x = x + 1;
} while( x < 20 );
}
}
Looping
x = 10
while True:
print(x)
x = x + 1
if x > 19:
break
public class Main {
public static void main(String[] args) {
int i, j;
for(i = 1; i < 5; i++) {
System.out.println();
for(j = i; j > 0; j--) {
System.out.print(j + " ");
}
}
}
}
Input
age = input("Enter your age")
print("Entered age is ", age)
import java.util.Scanner;
class Main {
public static void main(String[] args) {
int age;
Scanner scanner = new Scanner(System.in);
System.out.println("Enter your age");
age = scanner.nextInt();
System.out.println("Entered age is " + age);
}
}
Classes
class Player:
def __init__(self, name, role, rating):
self.name = name
self.role = role
self.rating = rating
class Player {
String name;
String role;
int rating;
Player(String name, String role, int rating) {
this.name = name;
this.role = role;
this.rating = rating;
}
}
Creating Objects
class Player:
def __init__(self, name, role):
self.name = name
self.role = role
def getRole(self):
return self.role
dhoni = Player("Dhoni", 'wicket keeper')
yadav = Player("Yadav", 'bowler')
print(dhoni.getRole())
print(yadav.getRole())
Creating Objects
class Player {
String name;
String role;
Player(String name, String role) {
this.name = name;
this.role = role;
}
String getRole() {
return this.role;
}
}
class Main {
public static void main(String[] args) {
Player dhoni = new Player("Dhoni", "wicket keeper");
Player yadav = new Player("Yadav", "bowler");
System.out.println(dhoni.getRole());
System.out.println(yadav.getRole());
}
}
Creating Objects
class Player:
def __init__(self, name = "", role = ""):
self.name = name
self.role = role
def getRole(self):
return self.role
dhoni = Player()
yadav = Player("Yadav", 'bowler')
print(dhoni.getRole())
print(yadav.getRole())
class Player {
String name;
String role;
Player() {
}
Player(String name, String role) {
this.name = name;
this.role = role;
}
String getRole() {
return this.role;
}
}
class Main {
public static void main(String[] args) {
Player dhoni = new Player();
Player yadav = new Player("Yadav", "bowler");
System.out.println(dhoni.getRole());
System.out.println(yadav.getRole());
}
}
Creating Objects
Aggregation in Python
class Shoe:
def __init__(self, size):
self.size = size
class Player:
def __init__(self, name, shoe):
self.name = name
self.shoe = shoe
shoe_eight = Shoe(8)
shoe_seven = Shoe(7)
dhoni = Player("Dhoni", shoe_eight)
jaddu = Player("Jadeja", shoe_seven)
print(dhoni.shoe.size)
print(jaddu.shoe.size)
Aggregation in Java
class Shoe {
int size;
Shoe(int size) {
this.size = size;
}
}
class Player {
String name;
Shoe shoe;
Player(String name, Shoe shoe) {
this.name = name;
this.shoe = shoe;
}
}
class Main {
public static void main(String a[]) {
Shoe shoe_eight = new Shoe(8);
Shoe shoe_seven = new Shoe(7);
Player dhoni = new Player("Dhoni", shoe_eight);
Player jaddu = new Player("Jadeja", shoe_seven);
System.out.println(dhoni.shoe.size);
System.out.println(jaddu.shoe.size);
}
}
Googly
class Shoe:
def __init__(self, size):
self.size = size
class Player:
def __init__(self, name, shoe):
self.name = name
self.shoe = shoe
def displayShoe(self):
print(self.size)
class Shoe:
def __init__(self, size):
self.size = size
class Player:
def __init__(self, name, shoe):
self.name = name
self.shoe = shoe
def displayShoe(self):
print(self.shoe.size)
shoe_eight = Shoe(8)
shoe_seven = Shoe(7)
dhoni = Player("Dhoni", shoe_eight)
jaddu = Player("Jadeja", shoe_seven)
dhoni.displayShoe()
jaddu.displayShoe()
Swapped?
class Shoe:
def __init__(self, size):
self.size = size
class Player:
def __init__(self, name, shoe):
self.name = name
self.shoe = shoe
def swap(self, other):
other = self
shoe_eight = Shoe(8)
shoe_seven = Shoe(7)
dhoni = Player("Dhoni", shoe_eight)
jaddu = Player("Jadeja", shoe_seven)
dhoni.swap(jaddu)
print(dhoni.shoe.size)
print(jaddu.shoe.size)
class Shoe {
int size;
Shoe(int size) {
this.size = size;
}
}
class Player {
String name;
Shoe shoe;
Player(String name, Shoe shoe) {
this.name = name;
this.shoe = shoe;
}
void swapShoe(Player other) {
other.shoe = this.shoe;
}
}
class Main {
public static void main(String a[]) {
Shoe shoe_eight = new Shoe(8);
Shoe shoe_seven = new Shoe(7);
Player dhoni = new Player("Dhoni", shoe_eight);
Player jaddu = new Player("Jadeja", shoe_seven);
dhoni.swapShoe(jaddu);
System.out.println(dhoni.shoe.size);
System.out.println(jaddu.shoe.size);
}
}
Swapped?
Association in Python
class Bat:
def __init__(self, company):
self.company = company
class Player:
def __init__(self, name):
self.name = name
def batting(self, bat):
print("I use " + bat.company)
mrf = Bat("MRF Bat");
ss = Bat("SS Bat");
sachin = Player("Dhoni")
dhoni = Player("Jadeja")
dhoni.batting(mrf)
sachin.batting(ss)
class Bat {
String company;
Bat(String company) {
this.company = company;
}
}
class Player {
String name;
Player(String name) {
this.name = name;
}
void batting(Bat bat) {
System.out.print("I use ");
System.out.println(bat.company);
}
}
class Main {
public static void main(String a[]) {
Bat mrf = new Bat("MRF Bat");
Bat ss = new Bat("SS Bat");
Player dhoni = new Player("Dhoni", ss);
Player sachin = new Player("Sachin", mrf);
sachin.batting(mrf);
dhoni.batting(ss);
}
}
Association in Java
Difference between association & aggregation
Instance Variable
Local Variable
Inheritance
class Employee:
def __init__(self, id):
self.id = id
class FullTime(Employee):
def __init__(self, id, name):
super().__init__(id)
self.name = name
def printDetails(self):
print(self.id, self.name)
aravind = FullTime(1001, "Aravind")
raghavan = FullTime(1002, "Raghavan")
aravind.printDetails()
raghavan.printDetails()
Inheritance
class Employee {
int id;
Employee(int id) {
this.id = id;
}
}
class FullTime extends Employee {
String name;
FullTime(int id, String name) {
super(id);
this.name = name;
}
void printDetails() {
System.out.print(this.id);
System.out.println(this.name);
}
}
class Main {
public static void main(String a[]) {
FullTime aravind = new FullTime(1001, "Aravind");
FullTime raghavan = new FullTime(1002, "Raghavan");
aravind.printDetails();
raghavan.printDetails();
}
}
Inheritance
class Employee:
def __init__(self, id, private):
self.id = id
self.__private = private
class FullTime(Employee):
def __init__(self, id, name):
super().__init__(id, "Something")
self.name = name
def printDetails(self):
print(self.id, self.name)
aravind = FullTime(1001, "Aravind")
print(aravind.id)
print(aravind.__private) #print(aravind._Employee__private)
print(aravind.name)
Inheritance
class Employee {
private int id;
Employee(int id) {
this.id = id;
}
}
class FullTime extends Employee {
String name;
FullTime(int id, String name) {
super(id);
this.name = name;
}
}
class Main {
public static void main(String a[]) {
FullTime aravind = new FullTime(1001, "Aravind");
System.out.println(aravind.name);
System.out.println(aravind.id);
}
}
Access Specifiers in Java
Same Package Different Package
Inside Class Outside Class Inherited Classes Other Classes
public ✔ ✔ ✔ ✔
protected ✔ ✔ ✔ ✘
default ✔ ✔ ✘ ✘
private ✔ ✘ ✘ ✘
Calling inherited method
class Employee:
def __init__(self):
pass
def method(self):
print("I am here")
class FullTime(Employee):
def __init__(self):
self.method()
aravind = FullTime()
Calling inherited method
class Employee {
void method() {
System.out.println("I am here");
}
}
class FullTime extends Employee {
public FullTime() {
this.method();
}
}
class Demo01 {
public static void main(String a[]) {
FullTime aravind = new FullTime();
}
}
Dynamic Polymorphism
class Employee {
void method() {
System.out.println("I am here");
}
}
class FullTime extends Employee {
void method() {
System.out.println("FullTime");
}
void myMethod() {
System.out.println("myMethod");
}
}
class Demo01 {
public static void main(String a[]) {
Employee aravind = new FullTime();
aravind.method();
}
}
Dynamic Polymorphism
class Employee {
void method() {
System.out.println("I am here");
}
}
class FullTime extends Employee {
void method() {
System.out.println("FullTime");
}
void myMethod() {
System.out.println("myMethod");
}
}
class Demo01 {
public static void main(String a[]) {
Employee aravind = new FullTime();
aravind.myMethod();
}
}
Abstract class
from abc import ABC, abstractmethod
class Employee(ABC):
@abstractmethod
def work(self):
pass
class FullTime(Employee):
def work(self):
print("50Hrs")
class PartTime(Employee):
def work(self):
print("20Hrs")
aravind = FullTime()
aravind.work()
Abstract class
abstract class Employee {
abstract void work();
}
class FullTime extends Employee {
void work() {
System.out.println("50Hrs");
}
}
class PartTime extends Employee {
void work() {
System.out.println("20Hrs");
}
}
class Main {
public static void main(String a[]) {
FullTime aravind = new FullTime();
aravind.work();
}
}
Let’s ask
What happens if we didn’t
override the abstract method in
child?
What happens if we try to create
object for abstract class?
How can we call concrete
method from an abstract class?
Exceptions!
a = 5
b = 0
try:
c = a / b
print("No exception")
except:
print("Exception")
class Main {
public static void main(String args[]) {
int a = 5, b = 0;
try {
int c = a / b;
System.out.println("No exception");
} catch(Exception e) {
System.out.println("Exception");
}
}
}
Exceptions!
a = 5
b = 0
try:
c = a / b
print("No exception")
except:
print("Exception")
finally:
print("Anyways")
class Main {
public static void main(String args[]) {
int a = 5, b = 0;
try {
int c = a / b;
System.out.println("No exception");
} catch(Exception e) {
System.out.println("Exception");
} finally {
System.out.println("Anyways");
}
}
}
Our own exceptions
class
MyException(Exception):
pass
a = 5
b = 0
try:
raise MyException()
except:
print("Exception")
class MyException extends Exception {
}
class Main {
public static void main(String args[]) {
try {
throw new MyException();
} catch(MyException e) {
System.out.println("Exception");
}
}
}
Our own exceptions
def someFun():
raise Exception()
try:
someFun()
except:
print("Exception")
class Main {
public static void method() throws Exception {
throw new Exception();
}
public static void main(String args[]) {
try {
Main.method();
} catch(Exception e) {
System.out.println("Exception");
}
}
}
About a static
class Animal:
def walk():
print("Static method")
dog = Animal()
Animal.walk()
dog.walk()
class Animal {
public static void method() {
System.out.println("Static method");
}
}
class Main {
public static void main(String[] args) {
Animal dog = new Animal();
dog.method();
Animal.method();
}
}
About a final
class Animal {
final int age = 5;
}
class Main {
public static void main(String[] args) {
Animal dog = new Animal();
dog.age = 10;
}
}
About a final
class Animal {
int age = 5;
final void method() {
System.out.println("A Method");
}
}
class Dog extends Animal {
void method() {
System.out.println("D Method");
}
}
class Main {
public static void main(String[] args) {
Dog dog = new Dog();
dog.method();
}
}
About a final
final class Animal {
int age = 5;
void method() {
System.out.println("A Method");
}
}
class Dog extends Animal {
void method() {
System.out.println("D Method");
}
}
class Main {
public static void main(String[] args) {
Dog dog = new Dog();
dog.method();
}
}
Creating connection
import mysql.connector
mydb = mysql.connector.connect(
host="localhost", user="root", passwd="", database="test"
)
print(mydb)
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
class Demo01 {
public static void main(String[] args) throws Exception {
Class.forName("com.mysql.jdbc.Driver");
String conn = "jdbc:mysql://localhost:3306/test";
String user = "root";
String pwd = "";
Connection con = DriverManager.getConnection(conn, user, pwd);
Statement stmt = con.createStatement();
}
}
Selecting data
import mysql.connector
mydb = mysql.connector.connect(
host="localhost", user="root", passwd="", database="test"
)
mycursor = mydb.cursor()
mycursor.execute("select * from demo")
myresult = mycursor.fetchall()
for x in myresult:
print(x)
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select * from demo");
while(rs.next()) {
System.out.println(rs.getInt(1));
}
Inserting data
import mysql.connector
mydb = mysql.connector.connect(
host="localhost", user="root", passwd="", database="test"
)
mycursor = mydb.cursor()
sql = "insert into demo (id) values (%s)"
val = (4,)
mycursor.execute(sql, val)
mydb.commit()
print(mycursor.rowcount, "record inserted.")
PreparedStatement stmt=con.prepareStatement("insert into demo (id) values
(?)");
stmt.setInt(1,5);
int i=stmt.executeUpdate();
System.out.println(i+" records inserted.");
Updating data
import mysql.connector
mydb = mysql.connector.connect(
host="localhost", user="root", passwd="", database="test"
)
mycursor = mydb.cursor()
sql = "udpate demo set id = 1 where id = 2"
mycursor.execute(sql)
mydb.commit()
print(mycursor.rowcount, "record updated.")
PreparedStatement stmt=con.prepareStatement("update demo set id = (?)
where id = 4");
stmt.setInt(1,5);
int i=stmt.executeUpdate();
System.out.println(i+" records inserted.");
Hashing the passwords
import hashlib
result = hashlib.md5(b'MyPassword')
print("Hashed Password ", end ="")
print(result.hexdigest())
String myPassword = "MyPassword";
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] messageDigest = md.digest(myPassword.getBytes());
BigInteger no = new BigInteger(1, messageDigest);
String hashtext = no.toString(16);
while (hashtext.length() < 32) {
hashtext = "0" + hashtext;
}
System.out.println("Hashed Password: " + hashtext);
Encrypting a string
String key = "someKey";
String initVector = "someIntVec";
String myPassword = "MyPassword";
IvParameterSpec iv = new IvParameterSpec(initVector.getBytes("UTF-8"));
SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
byte[] encrypted = cipher.doFinal(myPassword.getBytes());
String encryptedString = Base64.getEncoder().encodeToString(encrypted);
System.out.println(encryptedString);
cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
byte[] original =
cipher.doFinal(Base64.getDecoder().decode(encryptedString));
System.out.println(new String(original));
Encrypting a string
from cryptography.fernet import Fernet
message = "my deep dark secret".encode()
key = Fernet.generate_key()
f = Fernet(key)
encrypted = f.encrypt(message)
print(encrypted)
decrypted = f.decrypt(encrypted)
print(decrypted.decode())
File Writing
fo = open("E:/output.txt", "a")
fo.write( "Text from pythonn")
fo.close()
String str = "My text is heren";
FileWriter fw=new FileWriter("E:/output.txt", true);
for (int i = 0; i < str.length(); i++)
fw.write(str.charAt(i));
System.out.println("Writing successful");
fw.close();
File Reading
fo = open("E:/output.txt", "r")
for x in fo:
print(x)
fo.close()
File file = new File("E:/output.txt");
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
String line;
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
fileReader.close();
Threads in Python
import threading
import time
fo = open("E:/output.txt", "a")
def jobA():
for x in range(1, 999):
fo.write("An")
if x % 100 == 0:
time.sleep(1)
print("Some random job A")
def jobB():
for x in range(1, 999):
fo.write("Booooooon")
if x % 100 == 0:
time.sleep(1)
print("Some random job B")
Threads in Python
t1 = threading.Thread(target=jobA)
t2 = threading.Thread(target=jobB)
t1.start()
t2.start()
t1.join()
t2.join()
fo.close()
Threads in Java
class Multi extends Thread{
public void run(){
for(int i = 0; i < 999; i++) {
System.out.println(Thread.currentThread().getName());
if(i % 100 == 0) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
Threads in Java
class Main {
public static void main(String[] args) throws Exception {
Multi t1=new Multi();
t1.setName("A");
Multi t2 = new Multi();
t2.setName("Booooo");
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println("Done!");
}
}
Introduction
WEB SERVER
WEB CLIENT
HTTP REQUEST
HTTP RESPONSE
Process
1
R
e
c
e
i
v
e
t
h
e
r
e
q
u
e
s
t
2
S
e
a
r
c
h
f
o
r
t
h
e
f
i
l
e
3
P
r
o
v
i
d
e
t
h
e
r
e
s
p
o
n
s
e
Web Server
Getting python CGI right
Check in browser
Add shebang line
&
Execute your python
Start Apache
Download XAMPP
Install
Run & start apache
Config apache
Open
xampp/apache/conf/http
d.conf
Add AddHandler
cgi-script .py
ScriptInterpreterSource
Registry-Strict
at the end of the file
First CGI Page
#!C:/Users/Aravind/AppData/Local/Programs/Python/Python36-32/python.exe
print("Content-type:text/htmlrnrn")
print('<html>')
print('<head>')
print('<title>Hello Word - First CGI Program</title>')
print('</head>')
print('<body>')
print('<h2>Hello Word! This is my first CGI program</h2>')
print('</body>')
print('</html>')
How about this form?
#!C:/Users/Aravind/AppData/Local/Programs/Python/Python36-32/python.exe
print("Content-type:text/htmlrnrn")
print('''<form action="/hello_get.cgi" method="get">
First Name: <input type="text" name="first_name"> <br />
Last Name: <input type="text" name="last_name" />
<input type="submit" value="Submit" />
</form>
''')
How about this form?
#!C:/Users/Aravind/AppData/Local/Programs/Python/Python36-32/python.exe
print("Content-type:text/htmlrnrn")
print('''<form action="/hello_get.cgi" method="get">
First Name: <input type="text" name="first_name"> <br />
Last Name: <input type="text" name="last_name" />
<input type="submit" value="Submit" />
</form>
''')
Get in server
#!C:/Users/Aravind/AppData/Local/Programs/Python/Python36-32/python.exe
import cgi, cgitb
form = cgi.FieldStorage()
first_name = form.getvalue('first_name')
last_name = form.getvalue('last_name')
print("Content-type:text/htmlrnrn")
print("<html>")
print("<head>")
print("<title>Hello - Second CGI Program</title>")
print("</head>")
print("<body>")
print("<h2>Hello %s %s</h2>" % (first_name, last_name))
print("</body>")
print("</html>")
Lets have some cookies
#!C:/Users/Aravind/AppData/Local/Programs/Python/Python36-32/python.exe
print("Set-Cookie:UserID=XYZ;")
print("Set-Cookie:Password=XYZ123;")
print("Set-Cookie:Expires=Tuesday, 31-Dec-2007 23:12:40 GMT;")
print("Set-Cookie:Domain=localhost;")
print("Set-Cookie:Path=/perl;")
print("Content-type:text/htmlrnrn")
print('''I have set some cookie''')
Lets have some cookies
#!C:/Users/Aravind/AppData/Local/Programs/Python/Python36-32/python.exe
print("Set-Cookie:UserID=XYZ;")
print("Set-Cookie:Password=XYZ123;")
print("Set-Cookie:Expires=Tuesday, 31-Dec-2007 23:12:40 GMT;")
print("Set-Cookie:Domain=localhost;")
print("Set-Cookie:Path=/perl;")
print("Content-type:text/htmlrnrn")
print('''I have set some cookie''')
Reading the cookies
#!C:/Users/Aravind/AppData/Local/Programs/Python/Python36-32/python.exe
from os import environ
import cgi, cgitb
print("Content-type:text/htmlrnrn")
if environ['HTTP_COOKIE']:
allCookies = environ['HTTP_COOKIE'].split(';')
for cookie in allCookies:
print(cookie.split("="))
else:
print("no cookie")
Process
Run on Server
Create HTML / JSP
Run the file on server
Install Tomcat
Download Tomcat
Unzip the downloaded file
Create Dynamic Web
Create dynamic web
project
Select run time as
Tomcat with proper
version
First JSP page
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Java JSP Page</title>
</head>
<body>
<form action="process.jsp" method="get">
First Name: <input type="text" name="first_name"> <br />
Last Name: <input type="text" name="last_name" />
<input type="submit" value="Submit" />
</form>
</body>
</html>
Reading the data
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
String name=request.getParameter("first_name");
out.print("welcome "+name);
%>
</body>
</html>
Setting the cookie
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<body>
<%
Cookie cookie = new Cookie("UserID","1001");
response.addCookie(cookie);
%>
<form action="process.jsp" method="post">
First Name: <input type="text" name="first_name"> <br />
Last Name: <input type="text" name="last_name" />
<input type="submit" value="Submit" />
</form>
</body>
</html>
Reading the cookie
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<body>
<%
Cookie[] cookies = null;
cookies = request.getCookies();
if( cookies != null ) {
for (int i = 0; i < cookies.length; i++) {
out.print("Name : " + cookies[i].getName( ) + ", ");
out.print("Value: " + cookies[i].getValue( )+" <br/>");
}
}
%>
</body>
</html>
Thank You
https://codemithra.com
<Codemithra />

More Related Content

PDF
The_Ultimate_Java_CheatSheet.pdfjkrwogjw
awaissatti292
 
PDF
JAVA PRACTICE QUESTIONS v1.4.pdf
RohitkumarYadav80
 
PDF
Microsoft word java
Ravi Purohit
 
PDF
Java Programming Notes for Beginners by Arun Umrao
ssuserd6b1fd
 
PDF
Notes of Java
Arun Umrao
 
PPTX
Java fundamentals
HCMUTE
 
PDF
Java programming lab manual
sameer farooq
 
PPT
Core java
kasaragaddaslide
 
The_Ultimate_Java_CheatSheet.pdfjkrwogjw
awaissatti292
 
JAVA PRACTICE QUESTIONS v1.4.pdf
RohitkumarYadav80
 
Microsoft word java
Ravi Purohit
 
Java Programming Notes for Beginners by Arun Umrao
ssuserd6b1fd
 
Notes of Java
Arun Umrao
 
Java fundamentals
HCMUTE
 
Java programming lab manual
sameer farooq
 
Core java
kasaragaddaslide
 

Similar to Sharable_Java_Python.pdf (20)

PDF
Sam wd programs
Soumya Behera
 
PDF
Java_Programming_by_Example_6th_Edition.pdf
JayveeCultivo
 
PPTX
Java introduction
Samsung Electronics Egypt
 
PPSX
Java session4
Jigarthacker
 
DOCX
Java Program
Sudeep Singh
 
PPTX
Java notes 1 - operators control-flow
Mohammed Sikander
 
PDF
VTU Design and Analysis of Algorithms(DAA) Lab Manual by Nithin, VVCE, Mysuru...
Nithin Kumar,VVCE, Mysuru
 
PPTX
Kotlin
BoKaiRuan
 
PDF
2021 icse reducedsylabiix-computer applications
Vahabshaik Shai
 
PDF
Core java pract_sem iii
Niraj Bharambe
 
DOCX
All Of My Java Codes With A Sample Output.docx
adhitya5119
 
PPSX
DISE - Windows Based Application Development in Java
Rasan Samarasinghe
 
PDF
Week 5
EasyStudy3
 
PDF
Week 5
EasyStudy3
 
PDF
A comparison between C# and Java
Ali MasudianPour
 
PPTX
03 and 04 .Operators, Expressions, working with the console and conditional s...
Intro C# Book
 
PDF
Workshop Scala
Bert Van Vreckem
 
PDF
Java Fundamentals
Shalabh Chaudhary
 
PPTX
Java works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc.) I...
GANESHBABUVelu
 
PPTX
Object oriented programming1 Week 1.pptx
MirHazarKhan1
 
Sam wd programs
Soumya Behera
 
Java_Programming_by_Example_6th_Edition.pdf
JayveeCultivo
 
Java introduction
Samsung Electronics Egypt
 
Java session4
Jigarthacker
 
Java Program
Sudeep Singh
 
Java notes 1 - operators control-flow
Mohammed Sikander
 
VTU Design and Analysis of Algorithms(DAA) Lab Manual by Nithin, VVCE, Mysuru...
Nithin Kumar,VVCE, Mysuru
 
Kotlin
BoKaiRuan
 
2021 icse reducedsylabiix-computer applications
Vahabshaik Shai
 
Core java pract_sem iii
Niraj Bharambe
 
All Of My Java Codes With A Sample Output.docx
adhitya5119
 
DISE - Windows Based Application Development in Java
Rasan Samarasinghe
 
Week 5
EasyStudy3
 
Week 5
EasyStudy3
 
A comparison between C# and Java
Ali MasudianPour
 
03 and 04 .Operators, Expressions, working with the console and conditional s...
Intro C# Book
 
Workshop Scala
Bert Van Vreckem
 
Java Fundamentals
Shalabh Chaudhary
 
Java works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc.) I...
GANESHBABUVelu
 
Object oriented programming1 Week 1.pptx
MirHazarKhan1
 

Recently uploaded (20)

PPTX
ternal cell structure: leadership, steering
hodeeesite4
 
PPTX
Color Model in Textile ( RGB, CMYK).pptx
auladhossain191
 
PDF
Cryptography and Information :Security Fundamentals
Dr. Madhuri Jawale
 
PDF
Top 10 read articles In Managing Information Technology.pdf
IJMIT JOURNAL
 
PDF
The Effect of Artifact Removal from EEG Signals on the Detection of Epileptic...
Partho Prosad
 
PDF
FLEX-LNG-Company-Presentation-Nov-2017.pdf
jbloggzs
 
PDF
Queuing formulas to evaluate throughputs and servers
gptshubham
 
PDF
Principles of Food Science and Nutritions
Dr. Yogesh Kumar Kosariya
 
PPTX
easa module 3 funtamental electronics.pptx
tryanothert7
 
PPT
1. SYSTEMS, ROLES, AND DEVELOPMENT METHODOLOGIES.ppt
zilow058
 
PDF
Introduction to Data Science: data science process
ShivarkarSandip
 
PPTX
IoT_Smart_Agriculture_Presentations.pptx
poojakumari696707
 
PPTX
Module2 Data Base Design- ER and NF.pptx
gomathisankariv2
 
PDF
Introduction to Ship Engine Room Systems.pdf
Mahmoud Moghtaderi
 
PDF
July 2025: Top 10 Read Articles Advanced Information Technology
ijait
 
PPTX
MT Chapter 1.pptx- Magnetic particle testing
ABCAnyBodyCanRelax
 
PDF
Unit I Part II.pdf : Security Fundamentals
Dr. Madhuri Jawale
 
PDF
flutter Launcher Icons, Splash Screens & Fonts
Ahmed Mohamed
 
PPTX
22PCOAM21 Session 2 Understanding Data Source.pptx
Guru Nanak Technical Institutions
 
PPTX
Civil Engineering Practices_BY Sh.JP Mishra 23.09.pptx
bineetmishra1990
 
ternal cell structure: leadership, steering
hodeeesite4
 
Color Model in Textile ( RGB, CMYK).pptx
auladhossain191
 
Cryptography and Information :Security Fundamentals
Dr. Madhuri Jawale
 
Top 10 read articles In Managing Information Technology.pdf
IJMIT JOURNAL
 
The Effect of Artifact Removal from EEG Signals on the Detection of Epileptic...
Partho Prosad
 
FLEX-LNG-Company-Presentation-Nov-2017.pdf
jbloggzs
 
Queuing formulas to evaluate throughputs and servers
gptshubham
 
Principles of Food Science and Nutritions
Dr. Yogesh Kumar Kosariya
 
easa module 3 funtamental electronics.pptx
tryanothert7
 
1. SYSTEMS, ROLES, AND DEVELOPMENT METHODOLOGIES.ppt
zilow058
 
Introduction to Data Science: data science process
ShivarkarSandip
 
IoT_Smart_Agriculture_Presentations.pptx
poojakumari696707
 
Module2 Data Base Design- ER and NF.pptx
gomathisankariv2
 
Introduction to Ship Engine Room Systems.pdf
Mahmoud Moghtaderi
 
July 2025: Top 10 Read Articles Advanced Information Technology
ijait
 
MT Chapter 1.pptx- Magnetic particle testing
ABCAnyBodyCanRelax
 
Unit I Part II.pdf : Security Fundamentals
Dr. Madhuri Jawale
 
flutter Launcher Icons, Splash Screens & Fonts
Ahmed Mohamed
 
22PCOAM21 Session 2 Understanding Data Source.pptx
Guru Nanak Technical Institutions
 
Civil Engineering Practices_BY Sh.JP Mishra 23.09.pptx
bineetmishra1990
 

Sharable_Java_Python.pdf

  • 1. <Codemithra /> Java & Python | Parallel Course
  • 2. Programming Paradigms Functional/procedural programming: Program is a list of instructions to the computer Object-oriented programming Program is composed of a collection objects that communicate with each other
  • 5. First Program print("Hello, World!") class Main { public static void main(String args[]){ System.out.println("Hello, World!"); } }
  • 6. a = 10 b = 10.4 c = "String" d = 'single quoted string' e = True print("a, b, c, d, e", a, b, c, d, e) class Main { public static void main(String[] args) { int a = 10; float b = 10.4f; String c = "String"; // Not possible // String d = 'String'; boolean e = true; System.out.println("a, b, c, e " + a + " " + b + " " + c + " " + e); } } Variables
  • 7. Numbers in Python a = 10 print(a, type(a)) a = float(a) print(a, type(a)) a = complex(a) print(a, type(a)) a = complex(a, a) print(a, type(a))
  • 8. Numbers in Java class Main { public static void main(String[] args) { Integer a = 10; Float b = 10.4f; Double c = 10.4d; System.out.println("a, b, c " + a + " " + b + " " + c); } }
  • 9. Number methods print("math.floor " , math.floor(81.5)); print("math.ceil " , math.ceil(81.5)); print("math.round " , math.round(81.5)); print("math.exp " , math.exp(3)); class Main { public static void main(String[] args) { System.out.println("Math.floor " + Math.floor(81.5)); System.out.println("Math.ceil " + Math.ceil(81.5)); System.out.println("Math.round " + Math.round(81.5)); System.out.println("Math.exp " + Math.exp(3)); } }
  • 10. Number methods print("math.abs " , math.abs(-6)); print("math.sqrt " , math.sqrt(81)); print("Integer.max " , max(5, 6)); print("Integer.min" , min(5, 6)); class Main { public static void main(String[] args) { System.out.println("Math.abs " + Math.abs(-6)); System.out.println("Math.sqrt " + Math.sqrt(81)); System.out.println("Integer.max " + Integer.max(5, 6)); System.out.println("Integer.min" + Integer.min(5, 6)); } }
  • 11. String methods str = "ethnus" print(str.endswith("nus")) print(str.startswith("eth")) print(str.isdigit()) print(str.isspace()) class Main { public static void main(String[] args) { String str = "ethnus tech"; Character c = '3'; System.out.println(str.endsWith("nus")); System.out.println(str.startsWith("eth")); System.out.println(Character.isDigit(c)); System.out.println(Character.isSpace(c)); } }
  • 12. String methods str = "ethnus" print(str.upper()) print(str.lower()) class Main { public static void main(String[] args) { String str = "ethnus tech"; System.out.println(str.toUpperCase()); System.out.println(str.toLowerCase()); } }
  • 13. Arithmetic Operators print(a + b) System.out.println(a + b) 110 print(a - b) System.out.println(a - b) 90 print(a / b) System.out.println((float) a / b) 10.0 print(a * b) System.out.println(a * b) 1000 print(a ** b) System.out.println(Math.pow(a, b)) 100000000000000000000 print(a // b) System.out.println(a / b) 10 print(a % b) System.out.println(a % b) 0 a = 100, b = 10
  • 14. Comparison Operators print(a == b) System.out.print(a == b) False print(a > b) System.out.print(a > b) True print(a >= b) System.out.print(a >= b) True print(a < b) System.out.print(a < b) False print(a <= b) System.out.print(a <= b) False print(a != b) System.out.print(a != b) True print(a == b) System.out.print(a == b) False a = 100, b = 10
  • 15. Bitwise Operators print(a & b) System.out.print(a & b) 0 print(a | b) System.out.print(a | b) 6 print(a << 1) System.out.print(a << 1) 4 print(a >> 1) System.out.print(a >> 1) 1 print(a ^ b) System.out.print(a ^ b) 6 a = 2, b = 4
  • 16. Logical Operators print(a and b) System.out.print(a && b) False print(a or b) System.out.print(a || b) True print(not a) System.out.print(!a) False a = True, b = False
  • 17. Ternary Operator a = 100 b = 10 min = a < b and a or b print(min) class Main { public static void main(String[] args) { int a = 100; int b = 10; int min = a < b ? a : b; System.out.println(min); } }
  • 18. Branching a = '' if a: print("Value of a = ", a) else: print("False value in a") a = 0 if a: print("Value of a = ", a) else: print("False value in a") a = -1 if a: print("Value of a = ", a) else: print("False value in a") a = False if a: print("Value of a = ", a) else: print("False value in a")
  • 19. Branching class Main { public static void main(String[] args) { boolean a = true; if(a) System.out.println("A is true"); else System.out.println("A is false"); } } class Main { public static void main(String[] args) { int a = 5; if(a) System.out.println("A is true"); else System.out.println("A is false"); } }
  • 20. Branching a = 5 if a: print("a is not False") if a > 3: print("a is greater than 3") else: print("a is lesser than or equal to 3") class Main { public static void main(String[] args) { int a = 5; if(a > 0) { if(a > 3) { System.out.println("a is greater than 3"); } else { System.out.println("a is greater than 3"); } } } }
  • 21. Branching public class Main { public static void main(String[] args) { char grade = 'B'; switch(grade) { case 'A' : System.out.println("Excellent!"); break; case 'B' : case 'C' : System.out.println("Well done"); break; case 'D' : System.out.println("You passed"); break; default : System.out.println("Invalid grade"); } System.out.println("Your grade is " + grade); } }
  • 22. Looping count = 0 while (count < 9): print(count) count = count + 1 class Main { public static void main(String[] args) { int count = 0; while (count < 9) { System.out.println(count); count = count + 1; } } }
  • 23. Looping count = 0 while (count < 9): if count == 4: count = count + 1 continue print(count) count = count + 1 class Main { public static void main(String[] args) { int count = 0; while (count < 9) { if(count == 4) { count = count + 1; continue; } System.out.println(count); count = count + 1; } } }
  • 24. Looping count = 0 for count in range(0,9): if count == 4: continue print(count) class Main { public static void main(String[] args) { int count; for(count = 0; count < 9; count++) { if (count == 4) continue; System.out.println(count); } } } count = 0 for count in range(0,9): if count == 4: break print(count) class Main { public static void main(String[] args) { int count; for(count = 0; count < 9; count++) { if (count == 4) break; System.out.println(count); } } }
  • 25. Looping count = 0 for count in range(0,9): if count == 4: continue else: print(count) class Main { public static void main(String[] args) { int count; for(count = 0; count < 9; count++) { if (count == 4) continue; else System.out.println(count); } } } count = 0 for count in range(0,9): if count == 4: pass print(count) class Main { public static void main(String[] args) { int count; for(count = 0; count < 9; count++) { if (count == 4) { } System.out.println(count); } } }
  • 26. Looping x = 10 while True: print(x) x = x + 1 if x > 19: break public class Main { public static void main(String[] args) { int x = 10; do { System.out.print(x + "t"); x = x + 1; } while( x < 20 ); } }
  • 27. Looping x = 10 while True: print(x) x = x + 1 if x > 19: break public class Main { public static void main(String[] args) { int i, j; for(i = 1; i < 5; i++) { System.out.println(); for(j = i; j > 0; j--) { System.out.print(j + " "); } } } }
  • 28. Input age = input("Enter your age") print("Entered age is ", age) import java.util.Scanner; class Main { public static void main(String[] args) { int age; Scanner scanner = new Scanner(System.in); System.out.println("Enter your age"); age = scanner.nextInt(); System.out.println("Entered age is " + age); } }
  • 29. Classes class Player: def __init__(self, name, role, rating): self.name = name self.role = role self.rating = rating class Player { String name; String role; int rating; Player(String name, String role, int rating) { this.name = name; this.role = role; this.rating = rating; } }
  • 30. Creating Objects class Player: def __init__(self, name, role): self.name = name self.role = role def getRole(self): return self.role dhoni = Player("Dhoni", 'wicket keeper') yadav = Player("Yadav", 'bowler') print(dhoni.getRole()) print(yadav.getRole())
  • 31. Creating Objects class Player { String name; String role; Player(String name, String role) { this.name = name; this.role = role; } String getRole() { return this.role; } } class Main { public static void main(String[] args) { Player dhoni = new Player("Dhoni", "wicket keeper"); Player yadav = new Player("Yadav", "bowler"); System.out.println(dhoni.getRole()); System.out.println(yadav.getRole()); } }
  • 32. Creating Objects class Player: def __init__(self, name = "", role = ""): self.name = name self.role = role def getRole(self): return self.role dhoni = Player() yadav = Player("Yadav", 'bowler') print(dhoni.getRole()) print(yadav.getRole())
  • 33. class Player { String name; String role; Player() { } Player(String name, String role) { this.name = name; this.role = role; } String getRole() { return this.role; } } class Main { public static void main(String[] args) { Player dhoni = new Player(); Player yadav = new Player("Yadav", "bowler"); System.out.println(dhoni.getRole()); System.out.println(yadav.getRole()); } } Creating Objects
  • 34. Aggregation in Python class Shoe: def __init__(self, size): self.size = size class Player: def __init__(self, name, shoe): self.name = name self.shoe = shoe shoe_eight = Shoe(8) shoe_seven = Shoe(7) dhoni = Player("Dhoni", shoe_eight) jaddu = Player("Jadeja", shoe_seven) print(dhoni.shoe.size) print(jaddu.shoe.size)
  • 35. Aggregation in Java class Shoe { int size; Shoe(int size) { this.size = size; } } class Player { String name; Shoe shoe; Player(String name, Shoe shoe) { this.name = name; this.shoe = shoe; } } class Main { public static void main(String a[]) { Shoe shoe_eight = new Shoe(8); Shoe shoe_seven = new Shoe(7); Player dhoni = new Player("Dhoni", shoe_eight); Player jaddu = new Player("Jadeja", shoe_seven); System.out.println(dhoni.shoe.size); System.out.println(jaddu.shoe.size); } }
  • 36. Googly class Shoe: def __init__(self, size): self.size = size class Player: def __init__(self, name, shoe): self.name = name self.shoe = shoe def displayShoe(self): print(self.size) class Shoe: def __init__(self, size): self.size = size class Player: def __init__(self, name, shoe): self.name = name self.shoe = shoe def displayShoe(self): print(self.shoe.size) shoe_eight = Shoe(8) shoe_seven = Shoe(7) dhoni = Player("Dhoni", shoe_eight) jaddu = Player("Jadeja", shoe_seven) dhoni.displayShoe() jaddu.displayShoe()
  • 37. Swapped? class Shoe: def __init__(self, size): self.size = size class Player: def __init__(self, name, shoe): self.name = name self.shoe = shoe def swap(self, other): other = self shoe_eight = Shoe(8) shoe_seven = Shoe(7) dhoni = Player("Dhoni", shoe_eight) jaddu = Player("Jadeja", shoe_seven) dhoni.swap(jaddu) print(dhoni.shoe.size) print(jaddu.shoe.size)
  • 38. class Shoe { int size; Shoe(int size) { this.size = size; } } class Player { String name; Shoe shoe; Player(String name, Shoe shoe) { this.name = name; this.shoe = shoe; } void swapShoe(Player other) { other.shoe = this.shoe; } } class Main { public static void main(String a[]) { Shoe shoe_eight = new Shoe(8); Shoe shoe_seven = new Shoe(7); Player dhoni = new Player("Dhoni", shoe_eight); Player jaddu = new Player("Jadeja", shoe_seven); dhoni.swapShoe(jaddu); System.out.println(dhoni.shoe.size); System.out.println(jaddu.shoe.size); } } Swapped?
  • 39. Association in Python class Bat: def __init__(self, company): self.company = company class Player: def __init__(self, name): self.name = name def batting(self, bat): print("I use " + bat.company) mrf = Bat("MRF Bat"); ss = Bat("SS Bat"); sachin = Player("Dhoni") dhoni = Player("Jadeja") dhoni.batting(mrf) sachin.batting(ss)
  • 40. class Bat { String company; Bat(String company) { this.company = company; } } class Player { String name; Player(String name) { this.name = name; } void batting(Bat bat) { System.out.print("I use "); System.out.println(bat.company); } } class Main { public static void main(String a[]) { Bat mrf = new Bat("MRF Bat"); Bat ss = new Bat("SS Bat"); Player dhoni = new Player("Dhoni", ss); Player sachin = new Player("Sachin", mrf); sachin.batting(mrf); dhoni.batting(ss); } } Association in Java
  • 41. Difference between association & aggregation Instance Variable Local Variable
  • 42. Inheritance class Employee: def __init__(self, id): self.id = id class FullTime(Employee): def __init__(self, id, name): super().__init__(id) self.name = name def printDetails(self): print(self.id, self.name) aravind = FullTime(1001, "Aravind") raghavan = FullTime(1002, "Raghavan") aravind.printDetails() raghavan.printDetails()
  • 43. Inheritance class Employee { int id; Employee(int id) { this.id = id; } } class FullTime extends Employee { String name; FullTime(int id, String name) { super(id); this.name = name; } void printDetails() { System.out.print(this.id); System.out.println(this.name); } } class Main { public static void main(String a[]) { FullTime aravind = new FullTime(1001, "Aravind"); FullTime raghavan = new FullTime(1002, "Raghavan"); aravind.printDetails(); raghavan.printDetails(); } }
  • 44. Inheritance class Employee: def __init__(self, id, private): self.id = id self.__private = private class FullTime(Employee): def __init__(self, id, name): super().__init__(id, "Something") self.name = name def printDetails(self): print(self.id, self.name) aravind = FullTime(1001, "Aravind") print(aravind.id) print(aravind.__private) #print(aravind._Employee__private) print(aravind.name)
  • 45. Inheritance class Employee { private int id; Employee(int id) { this.id = id; } } class FullTime extends Employee { String name; FullTime(int id, String name) { super(id); this.name = name; } } class Main { public static void main(String a[]) { FullTime aravind = new FullTime(1001, "Aravind"); System.out.println(aravind.name); System.out.println(aravind.id); } }
  • 46. Access Specifiers in Java Same Package Different Package Inside Class Outside Class Inherited Classes Other Classes public ✔ ✔ ✔ ✔ protected ✔ ✔ ✔ ✘ default ✔ ✔ ✘ ✘ private ✔ ✘ ✘ ✘
  • 47. Calling inherited method class Employee: def __init__(self): pass def method(self): print("I am here") class FullTime(Employee): def __init__(self): self.method() aravind = FullTime()
  • 48. Calling inherited method class Employee { void method() { System.out.println("I am here"); } } class FullTime extends Employee { public FullTime() { this.method(); } } class Demo01 { public static void main(String a[]) { FullTime aravind = new FullTime(); } }
  • 49. Dynamic Polymorphism class Employee { void method() { System.out.println("I am here"); } } class FullTime extends Employee { void method() { System.out.println("FullTime"); } void myMethod() { System.out.println("myMethod"); } } class Demo01 { public static void main(String a[]) { Employee aravind = new FullTime(); aravind.method(); } }
  • 50. Dynamic Polymorphism class Employee { void method() { System.out.println("I am here"); } } class FullTime extends Employee { void method() { System.out.println("FullTime"); } void myMethod() { System.out.println("myMethod"); } } class Demo01 { public static void main(String a[]) { Employee aravind = new FullTime(); aravind.myMethod(); } }
  • 51. Abstract class from abc import ABC, abstractmethod class Employee(ABC): @abstractmethod def work(self): pass class FullTime(Employee): def work(self): print("50Hrs") class PartTime(Employee): def work(self): print("20Hrs") aravind = FullTime() aravind.work()
  • 52. Abstract class abstract class Employee { abstract void work(); } class FullTime extends Employee { void work() { System.out.println("50Hrs"); } } class PartTime extends Employee { void work() { System.out.println("20Hrs"); } } class Main { public static void main(String a[]) { FullTime aravind = new FullTime(); aravind.work(); } }
  • 53. Let’s ask What happens if we didn’t override the abstract method in child? What happens if we try to create object for abstract class? How can we call concrete method from an abstract class?
  • 54. Exceptions! a = 5 b = 0 try: c = a / b print("No exception") except: print("Exception") class Main { public static void main(String args[]) { int a = 5, b = 0; try { int c = a / b; System.out.println("No exception"); } catch(Exception e) { System.out.println("Exception"); } } }
  • 55. Exceptions! a = 5 b = 0 try: c = a / b print("No exception") except: print("Exception") finally: print("Anyways") class Main { public static void main(String args[]) { int a = 5, b = 0; try { int c = a / b; System.out.println("No exception"); } catch(Exception e) { System.out.println("Exception"); } finally { System.out.println("Anyways"); } } }
  • 56. Our own exceptions class MyException(Exception): pass a = 5 b = 0 try: raise MyException() except: print("Exception") class MyException extends Exception { } class Main { public static void main(String args[]) { try { throw new MyException(); } catch(MyException e) { System.out.println("Exception"); } } }
  • 57. Our own exceptions def someFun(): raise Exception() try: someFun() except: print("Exception") class Main { public static void method() throws Exception { throw new Exception(); } public static void main(String args[]) { try { Main.method(); } catch(Exception e) { System.out.println("Exception"); } } }
  • 58. About a static class Animal: def walk(): print("Static method") dog = Animal() Animal.walk() dog.walk() class Animal { public static void method() { System.out.println("Static method"); } } class Main { public static void main(String[] args) { Animal dog = new Animal(); dog.method(); Animal.method(); } }
  • 59. About a final class Animal { final int age = 5; } class Main { public static void main(String[] args) { Animal dog = new Animal(); dog.age = 10; } }
  • 60. About a final class Animal { int age = 5; final void method() { System.out.println("A Method"); } } class Dog extends Animal { void method() { System.out.println("D Method"); } } class Main { public static void main(String[] args) { Dog dog = new Dog(); dog.method(); } }
  • 61. About a final final class Animal { int age = 5; void method() { System.out.println("A Method"); } } class Dog extends Animal { void method() { System.out.println("D Method"); } } class Main { public static void main(String[] args) { Dog dog = new Dog(); dog.method(); } }
  • 62. Creating connection import mysql.connector mydb = mysql.connector.connect( host="localhost", user="root", passwd="", database="test" ) print(mydb) import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; class Demo01 { public static void main(String[] args) throws Exception { Class.forName("com.mysql.jdbc.Driver"); String conn = "jdbc:mysql://localhost:3306/test"; String user = "root"; String pwd = ""; Connection con = DriverManager.getConnection(conn, user, pwd); Statement stmt = con.createStatement(); } }
  • 63. Selecting data import mysql.connector mydb = mysql.connector.connect( host="localhost", user="root", passwd="", database="test" ) mycursor = mydb.cursor() mycursor.execute("select * from demo") myresult = mycursor.fetchall() for x in myresult: print(x) Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery("select * from demo"); while(rs.next()) { System.out.println(rs.getInt(1)); }
  • 64. Inserting data import mysql.connector mydb = mysql.connector.connect( host="localhost", user="root", passwd="", database="test" ) mycursor = mydb.cursor() sql = "insert into demo (id) values (%s)" val = (4,) mycursor.execute(sql, val) mydb.commit() print(mycursor.rowcount, "record inserted.") PreparedStatement stmt=con.prepareStatement("insert into demo (id) values (?)"); stmt.setInt(1,5); int i=stmt.executeUpdate(); System.out.println(i+" records inserted.");
  • 65. Updating data import mysql.connector mydb = mysql.connector.connect( host="localhost", user="root", passwd="", database="test" ) mycursor = mydb.cursor() sql = "udpate demo set id = 1 where id = 2" mycursor.execute(sql) mydb.commit() print(mycursor.rowcount, "record updated.") PreparedStatement stmt=con.prepareStatement("update demo set id = (?) where id = 4"); stmt.setInt(1,5); int i=stmt.executeUpdate(); System.out.println(i+" records inserted.");
  • 66. Hashing the passwords import hashlib result = hashlib.md5(b'MyPassword') print("Hashed Password ", end ="") print(result.hexdigest()) String myPassword = "MyPassword"; MessageDigest md = MessageDigest.getInstance("MD5"); byte[] messageDigest = md.digest(myPassword.getBytes()); BigInteger no = new BigInteger(1, messageDigest); String hashtext = no.toString(16); while (hashtext.length() < 32) { hashtext = "0" + hashtext; } System.out.println("Hashed Password: " + hashtext);
  • 67. Encrypting a string String key = "someKey"; String initVector = "someIntVec"; String myPassword = "MyPassword"; IvParameterSpec iv = new IvParameterSpec(initVector.getBytes("UTF-8")); SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES"); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING"); cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv); byte[] encrypted = cipher.doFinal(myPassword.getBytes()); String encryptedString = Base64.getEncoder().encodeToString(encrypted); System.out.println(encryptedString); cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING"); cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv); byte[] original = cipher.doFinal(Base64.getDecoder().decode(encryptedString)); System.out.println(new String(original));
  • 68. Encrypting a string from cryptography.fernet import Fernet message = "my deep dark secret".encode() key = Fernet.generate_key() f = Fernet(key) encrypted = f.encrypt(message) print(encrypted) decrypted = f.decrypt(encrypted) print(decrypted.decode())
  • 69. File Writing fo = open("E:/output.txt", "a") fo.write( "Text from pythonn") fo.close() String str = "My text is heren"; FileWriter fw=new FileWriter("E:/output.txt", true); for (int i = 0; i < str.length(); i++) fw.write(str.charAt(i)); System.out.println("Writing successful"); fw.close();
  • 70. File Reading fo = open("E:/output.txt", "r") for x in fo: print(x) fo.close() File file = new File("E:/output.txt"); FileReader fileReader = new FileReader(file); BufferedReader bufferedReader = new BufferedReader(fileReader); String line; while ((line = bufferedReader.readLine()) != null) { System.out.println(line); } fileReader.close();
  • 71. Threads in Python import threading import time fo = open("E:/output.txt", "a") def jobA(): for x in range(1, 999): fo.write("An") if x % 100 == 0: time.sleep(1) print("Some random job A") def jobB(): for x in range(1, 999): fo.write("Booooooon") if x % 100 == 0: time.sleep(1) print("Some random job B")
  • 72. Threads in Python t1 = threading.Thread(target=jobA) t2 = threading.Thread(target=jobB) t1.start() t2.start() t1.join() t2.join() fo.close()
  • 73. Threads in Java class Multi extends Thread{ public void run(){ for(int i = 0; i < 999; i++) { System.out.println(Thread.currentThread().getName()); if(i % 100 == 0) { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } } }
  • 74. Threads in Java class Main { public static void main(String[] args) throws Exception { Multi t1=new Multi(); t1.setName("A"); Multi t2 = new Multi(); t2.setName("Booooo"); t1.start(); t2.start(); t1.join(); t2.join(); System.out.println("Done!"); } }
  • 78. Getting python CGI right Check in browser Add shebang line & Execute your python Start Apache Download XAMPP Install Run & start apache Config apache Open xampp/apache/conf/http d.conf Add AddHandler cgi-script .py ScriptInterpreterSource Registry-Strict at the end of the file
  • 79. First CGI Page #!C:/Users/Aravind/AppData/Local/Programs/Python/Python36-32/python.exe print("Content-type:text/htmlrnrn") print('<html>') print('<head>') print('<title>Hello Word - First CGI Program</title>') print('</head>') print('<body>') print('<h2>Hello Word! This is my first CGI program</h2>') print('</body>') print('</html>')
  • 80. How about this form? #!C:/Users/Aravind/AppData/Local/Programs/Python/Python36-32/python.exe print("Content-type:text/htmlrnrn") print('''<form action="/hello_get.cgi" method="get"> First Name: <input type="text" name="first_name"> <br /> Last Name: <input type="text" name="last_name" /> <input type="submit" value="Submit" /> </form> ''')
  • 81. How about this form? #!C:/Users/Aravind/AppData/Local/Programs/Python/Python36-32/python.exe print("Content-type:text/htmlrnrn") print('''<form action="/hello_get.cgi" method="get"> First Name: <input type="text" name="first_name"> <br /> Last Name: <input type="text" name="last_name" /> <input type="submit" value="Submit" /> </form> ''')
  • 82. Get in server #!C:/Users/Aravind/AppData/Local/Programs/Python/Python36-32/python.exe import cgi, cgitb form = cgi.FieldStorage() first_name = form.getvalue('first_name') last_name = form.getvalue('last_name') print("Content-type:text/htmlrnrn") print("<html>") print("<head>") print("<title>Hello - Second CGI Program</title>") print("</head>") print("<body>") print("<h2>Hello %s %s</h2>" % (first_name, last_name)) print("</body>") print("</html>")
  • 83. Lets have some cookies #!C:/Users/Aravind/AppData/Local/Programs/Python/Python36-32/python.exe print("Set-Cookie:UserID=XYZ;") print("Set-Cookie:Password=XYZ123;") print("Set-Cookie:Expires=Tuesday, 31-Dec-2007 23:12:40 GMT;") print("Set-Cookie:Domain=localhost;") print("Set-Cookie:Path=/perl;") print("Content-type:text/htmlrnrn") print('''I have set some cookie''')
  • 84. Lets have some cookies #!C:/Users/Aravind/AppData/Local/Programs/Python/Python36-32/python.exe print("Set-Cookie:UserID=XYZ;") print("Set-Cookie:Password=XYZ123;") print("Set-Cookie:Expires=Tuesday, 31-Dec-2007 23:12:40 GMT;") print("Set-Cookie:Domain=localhost;") print("Set-Cookie:Path=/perl;") print("Content-type:text/htmlrnrn") print('''I have set some cookie''')
  • 85. Reading the cookies #!C:/Users/Aravind/AppData/Local/Programs/Python/Python36-32/python.exe from os import environ import cgi, cgitb print("Content-type:text/htmlrnrn") if environ['HTTP_COOKIE']: allCookies = environ['HTTP_COOKIE'].split(';') for cookie in allCookies: print(cookie.split("=")) else: print("no cookie")
  • 86. Process Run on Server Create HTML / JSP Run the file on server Install Tomcat Download Tomcat Unzip the downloaded file Create Dynamic Web Create dynamic web project Select run time as Tomcat with proper version
  • 87. First JSP page <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html> <html> <head> <meta charset="ISO-8859-1"> <title>Java JSP Page</title> </head> <body> <form action="process.jsp" method="get"> First Name: <input type="text" name="first_name"> <br /> Last Name: <input type="text" name="last_name" /> <input type="submit" value="Submit" /> </form> </body> </html>
  • 88. Reading the data <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html> <html> <head> <meta charset="ISO-8859-1"> <title>Insert title here</title> </head> <body> <% String name=request.getParameter("first_name"); out.print("welcome "+name); %> </body> </html>
  • 89. Setting the cookie <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html> <html> <body> <% Cookie cookie = new Cookie("UserID","1001"); response.addCookie(cookie); %> <form action="process.jsp" method="post"> First Name: <input type="text" name="first_name"> <br /> Last Name: <input type="text" name="last_name" /> <input type="submit" value="Submit" /> </form> </body> </html>
  • 90. Reading the cookie <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html> <html> <body> <% Cookie[] cookies = null; cookies = request.getCookies(); if( cookies != null ) { for (int i = 0; i < cookies.length; i++) { out.print("Name : " + cookies[i].getName( ) + ", "); out.print("Value: " + cookies[i].getValue( )+" <br/>"); } } %> </body> </html>