SlideShare uma empresa Scribd logo
1 de 108
Let’s code in Java
AASHISH JAIN
Session-1
 Introduction to Basic Java
 Java Fundamentals
 Essentials of Object-Oriented Programming
 Packages
Introduction to Basic Java
 Java is a high-level, object-oriented, robust and secure programming language.
 James Gosling, Mike Sheridan and Patrick Naughton (popularly known as Green
Team) developed Java in 1991.
 In the beginning, the language was named as ‘Oak’, but later in 1995, Oak was
renamed to Java by Sun microsystems.
 Different types of computer applications like standalone applications, web
applications, enterprise applications and mobile applications can be developed
with the help of Java
 According to Sun Microsystems, more than 3 billion devices run Java.
Introduction to Basic Java
Coding Problems Java Solution
Pointers references (“safe” pointers)
memory leaks garbage collection
error handling exception handling
complexity reusable code in APIs
platform dependent portable code
WHY JAVA?
….plus
Security,
networking,
multithreading,
web
programming
and so on..
Features of Java
 Architecture neutral
 Dynamic
 Interpreted
 High Performance
 Multithreaded
 Distributed
 Simple
 Object-Oriented
 Portable
 Platform independent
 Secured
 Robust
Introduction to Basic Java
JDK, JRE, JVM
Introduction to Basic Java
Internal detail of JVM
Introduction to Basic Java
 Class loader loads the class files.
 Method area stores pre-class structures as the
runtime constant pool.
 Heap is the runtime data area in which objects
are allocated.
 Stack holds local variables and partial results
 PC Register contains the address of the JVM
instruction currently being executed.
 Native method stack contains all the native
methods used in the application.
A sample Java Program
Introduction to Basic Java
Source Code
Create/Modify Source Code
Compile Source Code
i.e., javac Welcome.java
Bytecode
Run Byteode
i.e., java Welcome
Result
If compilation errors
If runtime errors or incorrect result
public class Welcome {
public static void main(String[] args) {
System.out.println("Welcome to Java!");
}
}
…
Method Welcome()
0 aload_0
…
Method void main(java.lang.String[])
0 getstatic #2 …
3 ldc #3 <String "Welcome to
Java!">
5 invokevirtual #4 …
8 return
Saved on the disk
stored on the disk
Source code (developed by the programmer)
Byte code (generated by the compiler for JVM
to read and interpret, not for you to understand)
Variables
Introduction to Basic Java
 A container which holds the value while the java program is executed.
 Assigned with a datatype
 Combination of vary + able that means it’s value can be changed.
class A{
int data=50;//instance variable
static int m=100;//static variable
void method(){
int n=90;//local variable
} }
variable
Local variable Instance variable Static variable
Java Fundamentals
Data types
Data types
Data Type Default Value Default size
boolean false 1 bit
char 'u0000' 2 byte
byte 0 1 byte
short 0 2 byte
int 0 4 byte
long 0L 8 byte
float 0.0f 4 byte
double 0.0d 8 byte
Java Fundamentals
Operators
Operator in java is a symbol that is used to perform operations. For example: +, -, *, / etc.
There are many types of operators in java which are given below:
Java Fundamentals
 Unary Operator,
 Arithmetic Operator,
 Shift Operator,
 Relational Operator,
 Bitwise Operator,
 Logical Operator,
 Ternary Operator,
 Assignment Operator,
Unary Operators
Unary operators require only one operand. These are used to perform following operations:
 Incrementing/decrementing a value by one
 Negating an expression
 Inverting the value of a Boolean
Java Fundamentals
class OperatorExample{
public static void main(String args[]){ i
nt x=10, a=10;
boolean c=true;
System.out.println(x++);//10 (11)
System.out.println(++x);//12
System.out.println(x--);//12 (11)
System.out.println(--x);//10
System.out.println(~a);//-11
System.out.println(!c);//false
}}
Arithmetic Operators
Arithmetic operators are used to perform basic math operations like addition, subtraction etc.
Java Fundamentals
class OperatorExample{
public static void main(String args[]){in
t a=10;
int b=5;
System.out.println(a+b);//15
System.out.println(a-b);//5
System.out.println(a*b);//50
System.out.println(a/b);//2
System.out.println(a%b);//0
}}
Shift Operators
Shift operators are used to perform following operations:
 << (left shift)
 >> (signed right shift)
 >>> (unsigned right shift)
Java Fundamentals
class OperatorExample{
public static void main(String args[]){
System.out.println(10<<2);//10*2^2=10*4=40
System.out.println(10<<3);//10*2^3=10*8=80
System.out.println(10>>2);//10/2^2=10/4=2
System.out.println(20>>2);//20/2^2=20/4=5
System.out.println(20>>>2); //5
System.out.println(-20>>>2); //1073741819
}}
Relational Operators
Relational operators are used for comparisons:
 <= (less than equal to)
 >= (greater than equal to)
 == (equals to)
 != (not equal to)
 < (less than)
 > (greater than)
 instanceof
Java Fundamentals
class OperatorExample{
public static void main(String args[]){in
t a=10;
int b=5;
System.out.println(a>b);//true
System.out.println(a<b);//false
System.out.println(a==b);//false
System.out.println(a!=b);//true
System.out.println(a>=b);//true
}}
Bitwise Operators
 | (Bitwise OR)
 & (Bitwise AND)
Java Fundamentals
class OperatorExample{
public static void main(String args[])
{int a=2;
int b=3;
System.out.println(a&b);//0010 & 001100102
System.out.println(a|b);// 0010 | 001100113
}}
Logical Operators
 && (Logical AND)
 || (Logical OR)
Java Fundamentals
class OperatorExample{
public static void main(String args[])
{int a=10;
int b=5;
System.out.println(a>b && a<b);//false
System.out.println(a>b || a<b);//true
}}
Ternary Operator
Ternary Operator is used as one liner replacement for if-then-else statement.
(condition)?(this block will execute in case of true):(this block will execute in case of false)
Java Fundamentals
class OperatorExample{
public static void main(String args[])
{int a=10;
int b=5;
Int c=a>b?a:b;
System.out.println(c);//10
}}
Assignment Operators
Assignment operators are used to assign the value on it’s right to the operand on it’s left.
Java Fundamentals
class OperatorExample{
public static void main(String args[]){in
t a=10;
a+=3;//10+3
System.out.println(a);
a-=4;//13-4
System.out.println(a);
a*=2;//9*2
System.out.println(a);
a/=2;//18/2
System.out.println(a);
}}
Control Statements
 if statement
 if-else statement
 nested if statement
 if-else-if ladder
 Switch statement
 For Loop
 While Loop
 Do-while Loop
Java Fundamentals
if Statement
if(condition){
//code to be executed
}
Java Fundamentals
public class IfExample {
public static void main(String[] args) {
//defining an 'age' variable
int age=20;
//checking the age
if(age>18){
System.out.print("Age is greater than 18");
}
}
}
If-else Statement
if(condition){
//code if condition is true
}else{
//code if condition is false
}
Java Fundamentals
public class IfElseExample {
public static void main(String[] args) {
//defining a variable
int number=13;
//Check if the number is divisible by 2 or not
if(number%2==0){
System.out.println("even number");
}else{
System.out.println("odd number");
}
}
}
Nested if Statement
if(condition){
//code to be executed
if(condition){
//code to be executed
}
}
Java Fundamentals
public class JavaNestedIfExample {
public static void main(String[] args) {
//Creating two variables for age and weight
int age=20;
int weight=80;
//applying condition on age and weight
if(age>=18){
if(weight>50){
System.out.println("You are eligible to don
ate blood");
}
}
}}
If-else-if Ladder
if(condition1){
//code to be executed if condition1 is true
}else if(condition2){
//code to be executed if condition2 is true
} else if(condition3){
//code to be executed if condition3 is true}
...
else{
//code to be executed if all the conditions are false}
Java Fundamentals
public class IfElseIfExample {
public static void main(String[] args) {
int marks=65;
if(marks<50){ System.out.println("fail"); }
else if(marks>=50 && marks<60){
System.out.println("D grade"); }
else if(marks>=60 && marks<70){
System.out.println("C grade"); }
else if(marks>=70 && marks<80){
System.out.println("B grade"); }
else if(marks>=80 && marks<90){
System.out.println("A grade"); }
else if(marks>=90 && marks<100){
System.out.println("A+ grade"); }
else{
System.out.println("Invalid!"); } } }
Switch Statement
switch(expression){
case value1:
//code to be executed;
break; //optional
case value2:
//code to be executed;
break; //optional
......
default:
code to be executed if all cases are not matched;}
Java Fundamentals
public class SwitchExample {
public static void main(String[] args) {
//Declaring a variable for switch expression
int number=20;
//Switch expression
switch(number){
case 10: System.out.println("10");
break;
case 20: System.out.println("20");
break;
case 30: System.out.println("30");
break;
//Default case statement
default:
System.out.println("Not in 10, 20 or 30");
} } }
For Loop
for(initialization;condition;incr/decr){
//statement or code to be executed
}
NOTE: If the number of iteration is fixed, it is recommended to use for loop.
Java Fundamentals
public class ForExample {
public static void main(String[] args) {
//Code of Java for loop
for(int i=1;i<=10;i++){
System.out.println(i);
} } }
while Loop
while(condition){
//code to be executed
}
NOTE: If the number of iteration is not fixed, it is recommended to use this loop.
Java Fundamentals
public class WhileExample {
public static void main(String[] args) {
int i=1;
while(i<=10){
System.out.println(i);
i++;
} } }
Do-while Loop
do{
//code to be executed
}while(condition);
NOTE: If the number of iteration is not fixed and the loop must have to be executed
at least once, it is recommended to use this loop.
Java Fundamentals
public class DoWhileExample {
public static void main(String[] args) {
int i=1;
do{
System.out.println(i);
i++;
}while(i<=10); } }
Break statement
Java Fundamentals
public class BreakExample {
public static void main(String[] args) {
//using for loop
for(int i=1;i<=10;i++){
if(i==5){
//breaking the loop
break;
}
System.out.println(i);
} } }
continue statement
Java Fundamentals
public class ContinueExample {
public static void main(String[] args) {
//for loop
for(int i=1;i<=10;i++){
if(i==5){
//using continue statement
continue;//it will skip the rest statement within this block
}
System.out.println(i);
} } }
Arrays
Java Fundamentals
 An object which contains elements of a similar data type.
 Elements are stored in contiguous memory location.
 Only fixed number of elements can be stored.
Arrays
Java Fundamentals
 Two types:
 Single Dimension Array
 Multidimensional Array
 Declaration:
 dataType[] arr; (or)
 dataType []arr; (or)
 dataType arr[];
 Instantiation:
 arrayRefVar=new datatype[size];
String
Java Fundamentals
 String is basically an object that represents sequence of character values.
 String in Java is immutable which means it cannot be changed. Whenever we change any string, a
new instance is created.
 The java.lang.String class is used to create a string object.
 Two ways to create String object:
 By String literal
 By new Keyword
By String literals
Java Fundamentals
 Created by using double quotes.
 String str=“Welcome”;
 Each time you create a string literal, JVM checks the “String constant
pool” first.
 If it already exists, a reference to the pooled instance is returned.
 If not, a new string instance is created and placed in the pool. For example:
 String s1=“Welcome”;
 String s2=“Welcome”;
By new keyword
Java Fundamentals
 String s=new String("Welcome");//creates two objects and one reference variable
 In such case, JVM will create a new string object in normal (non-pool) heap memory.
 The literal "Welcome" will be placed in the string constant pool.
 s will refer to the object in a heap (non-pool).
Operations on String
Java Fundamentals
public class StringExample{
public static void main(String args[]){
String str1=“Learn To Code";
String str2=“Java Programming";
System.out.println(str1.charAt(4));//prints the char value at the 4th index
System.out.println(str1.concat(str2));//concatenating one string
System.out.println(str1.compareTo(str2));//1
System.out.println(str1.contains(“To”));//true
System.out.println(str1.equals(str2));//false
System.out.println(str1.equalsIgnoreCase(str2));//false
System.out.println(str1.length());//13
}}
Enumerations (Enum)
Java Fundamentals
 The Enum is a data type which contains a fixed set of constants.
 Static and final implicitly.
class EnumExample{
//defining the enum inside the class
public enum Season { WINTER, SPRING, SUMMER, FALL }
public static void main(String[] args) {
//traversing the enum
for (Season s : Season.values())
System.out.println(s);
}}
Object and Class
Essentials of Object-Oriented Programming
 An object is the physical as well as logical
entity, whereas, a class is a logical entity only.
 An entity that has state (data/ value) and
behaviour (functionality) is known as object.
 A class is a template or blueprint from which
objects are created.
Inheritance
Essentials of Object-Oriented Programming
Naming convention
Essentials of Object-Oriented Programming
 A class/interface should start with uppercase letter e.g. Student, College, University etc.
 Class should be a noun and interface should be an adjective.
 A method should start with lowercase letter and/or followed by an uppercase letter e.g. draw(),
actionPerformed() etc.
 A variable should start with lowercase letter e.g. id, name, rollNo, etc.
 A package name should be in lowercase letter such as lang, io, net, etc.
 A constant should be in uppercase letters such as SUNDAY, MONDAY etc.
Class fundamentals
Essentials of Object-Oriented Programming
//Defining a Student class.
class Student{
//defining fields
int id;
//field or data member or instance variable
String name;
//creating main method inside the Student class
public static void main(String args[]){
//Creating an object or instance
Student s1=new Student();
//creating an object of Student
//Printing values of the object
System.out.println(s1.id);
//accessing member through reference variable
System.out.println(s1.name);
}
}
Class fundamentals
Essentials of Object-Oriented Programming
 There are three ways to initialize object:
 By reference variable
 By method
 By constructor
Class fundamentals: By reference variables
Essentials of Object-Oriented Programming
class Student{
int id;
String name; }
class TestStudent{
public static void main(String args[]){
Student s1=new Student();
s1.id=101;
s1.name="Sonoo";
System.out.println(s1.id+" "+s1.name);//printing members with a white space
} }
Class fundamentals: By method
Essentials of Object-Oriented Programming
class Student{
int rollno;
String name;
void insertRecord(int r, String n){
rollno=r;
name=n; }
void displayInformation()
{System.out.println(rollno+" "+name);} }
class TestStudent{
public static void main(String args[]){
Student s1=new Student();
Student s2=new Student();
s1.insertRecord(101,“Abhishek");
s2.insertRecord(202,"Anchit");
s1.displayInformation();
s2.displayInformation(); } }
Class fundamentals: By constructor
Essentials of Object-Oriented Programming
 A special type of method used to initialize the object.
 Constructor name must be same as its class name.
 It must have no explicit return type.
 It can not be abstract, static, final and synchronized.
 It can be of two types: default and parameterized
Class fundamentals: By constructor
Essentials of Object-Oriented Programming
class Student{
int id;
String name;
//creating a parameterized constructor
Student(int i,String n){
id = i;
name = n; }
//method to display the values
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
//creating objects and passing values
Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
//calling method to display the values of object
s1.display();
s2.display(); } }
Static keyword
Essentials of Object-Oriented Programming
 Used for memory management mainly.
 Can be applied with variables, methods,
blocks and nested classes.
this keyword
Essentials of Object-Oriented Programming
 Can be used to refer current class instance variable.
 Can be used to invoke current class methods.
 this() can be used to invoke current class constructor.
class A{
void m(){System.out.println("hello m");}
void n(){
System.out.println("hello n");
//m(); //same as this.m()
this.m();
} }
class TestThis{
public static void main(String args[]){
A a=new A();
a.n();
}}
final keyword
Essentials of Object-Oriented Programming
 Used to restrict the user.
 Can be applied to variable, method, and class.
class Bike{
final int speedlimit=90;//final variable
void run(){
speedlimit=400;
}
public static void main(String args[]){
Bike obj=new Bike ();
obj.run();
}
}
super keyword
Essentials of Object-Oriented Programming
 Used to refer immediate parent class object.
class Animal{
String color="white"; }
class Dog extends Animal{
String color="black";
void printColor(){
System.out.println(color);
//prints color of Dog class
System.out.println(super.color);
//prints color of Animal class
} }
class TestSuper{
public static void main(String args[]){
Dog d=new Dog();
d.printColor(); }}
Polymorphism
Essentials of Object-Oriented Programming
 It is a concept to perform a single action in different ways.
 Derived from Greek words: poly and morphs
which means many and forms respectively.
 Two types:
 Compile-time polymorphism (Overloading)
 Run-Time polymorphism (Overriding)
Method Overloading
Essentials of Object-Oriented Programming
 A class has multiple methods having same name but different in parameters, called as Method
Overloading.
class Adder{
static int add(int a,int b){return a+b;}
static int add(int a,int b,int c){return a+b+c;}
}
class TestOverloading1{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,11,11));
}}
Method Overriding
Essentials of Object-Oriented Programming
 If a subclass provides the specific implementation of the method that has been declared by one of
its parent class, known as method overriding.
class Vehicle{
void run(){System.out.println("Vehicle is running");}
}
//Creating a child class
class Bike extends Vehicle{
public static void main(String args[]){
//creating an instance of child class
Bike obj = new Bike();
//calling the method with child class instance
obj.run();
} }
Abstraction: Abstract class
Essentials of Object-Oriented Programming
 Abstraction is a process of hiding the
implementation details and showing only
functionality to the user.
 A class declared with abstract keyword is known
as abstract class.
 It can have abstract and non-abstract methods.
Abstraction: Abstract class
Essentials of Object-Oriented Programming
abstract class Bike{
abstract void run();
}
class Honda extends Bike{
void run(){System.out.println("running safely");
}
public static void main(String args[]){
Bike obj = new Honda4();
obj.run();
} }
Abstraction: Interface
Essentials of Object-Oriented Programming
 An interface is a blueprint of class.
 It has static constants and abstract methods.
 Represents IS-A relationship.
 Used to achieve abstraction, to support functionality of multiple inheritance, and to achieve loose
coupling.
 A class uses implements keyword to implement an interface.
interface printable{
void print();
}
class Example implements printable{ pu
blic void print(){
System.out.println("Hello");}
public static void main(String args[]){ Exa
mple obj = new Example();
obj.print();
} }
Abstraction: Abstract class V/S Interface
Essentials of Object-Oriented Programming
Abstract class Interface
Can have abstract and non-abstract methods Can have only abstract methods
Doesn’t support multiple inheritance Supports multiple inheritance
Can have static, non-static, final, and non-final
variables
Can have only static and final variables
Can provide the implementation of an interface Can’t provide the implementation of abstract class
Can extend multiple interfaces and an abstract Can extend interfaces only
Extended using keyword “extends” Implemented using keyword “implements”
What is a package?
Packages
 A group of similar types of classes, interfaces
and sub-packages.
 Categorized into two forms:
 Built-in packages
 User-defined packages
Why packages?
Packages
 To categorize classes and interfaces for easily maintenance.
 Provides access protection.
 Removes naming collision.
Create a package
Packages
 The package keyword is used to create a package in java.
 If no using an IDE, follow the syntax:
 javac –d directory javafilename, for e.g.:
 javac –d . Simple.java
 -d specifies the destination where to put the generated class file,
 To keep the package within the same directory, use . (dot)
 To compile: javac –d . Simple.Java
 To run: java mypack.Simple
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
} }
Access a package
Packages
 Following are the ways to access the package from outside the package:
 import package.*;
 import package.classname;
 Fully qualified name
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
} }
Understanding class path
Packages
 To compile:
 e:sources> javac -d c:classes A.java
 To run the program from e:sources:
 e:sources> set classpath=c:classes;.;
 e:sources> java mypack.A
 Another way to run this program:
 e:sources> java -classpath c:classes mypack.A
 -classpath switch temporary loads the class file
while it can be done permanent by setting
classpath in environment variable.
package mypack;
public class A{
public static void main(String args[]){
System.out.println("Welcome to package");
} }
Access modifiers and their scope
Packages
Access Modifiers Within class Within same
package
Within subclass of
other package
Within class of
other package
public Yes Yes Yes Yes
protected Yes Yes Yes No
default Yes Yes No No
private Yes No No No
Session-2
 Exception Handling
 I/O operations in Java
 Multithreaded Programming
 Network Programming
Exception Handling
 One of the powerful mechanism to handle the runtime errors so that normal flow of application
can be maintained.
 Three types of exceptions:
 Checked Exception
 Unchecked Exception
 Error
Exception Propagation
Exception Handling
Exception Handling
Exception Types
Exception Keywords
Exception Handling
 try: used to specify a block where exception code is placed. The try block must be followed by
either catch or finally block.
 catch: used to handle the exception. Must be preceded by try block and can be followed by finally
block.
 finally: used to execute the important code of the program. This block will always be executed
irrespective of the exception handled or not.
 throw: used to throw an exception.
 throws: used to declare exceptions. It doesn’t throw an exception rather it specifies an exception
may occur in this method.
public class JavaExceptionExample{
public static void main(String args[]){
try{
//code that may raise exception
int data=100/0;
}catch(ArithmeticException e){System.out.println(e);}
//rest code of the program
System.out.println("rest of the code...");
}
}
Exception Handling
public class TestThrow{
static void validate(int age){
if(age<18)
throw new ArithmeticException(“Age is not valid");
else
System.out.println("welcome to vote");
}
public static void main(String args[]){
validate(13);
System.out.println("rest of the code..."); } }
Usage of throw keyword
Exception Handling
import java.io.*;
class M{
void method()throws IOException{
System.out.println("device operation performed");
} }
class Testthrows{
public static void main(String args[])throws IOException{//declare exception
M m=new M();
m.method();
System.out.println("normal flow..."); }}
Usage of throws keyword
Exception Handling
class TestFinallyBlock{
public static void main(String args[]){
try{
int data=25/5;
System.out.println(data); }
catch(NullPointerException e){System.out.println(e);}
finally{System.out.println("finally block is always executed");}
System.out.println("rest of the code...");
} }
Usage of finally keyword
Exception Handling
class InvalidAgeException extends Exception{
InvalidAgeException(String s){
super(s);
}
}
User Defined Exception
class TestCustomException1{
static void validate(int age)throws InvalidAgeException{
if(age<18)
throw new InvalidAgeException(“Age is not valid");
else
System.out.println("welcome to vote");
}
public static void main(String args[]){
try{ validate(13); }
catch(Exception m)
{ System.out.println("Exception occured: "+m);}
System.out.println("rest of the code..."); }}
I/O operations in Java
 Java I/O (input/output) is used to process the input and produce the output.
 Java uses concept of streams to make I/O operations fast.
 The java.io package contains all the classes required for input and output operations.
 There are two types of streams which are further categorized into input and output streams:
 Byte Streams
 Character Streams
I/O operations in Java
Byte Streams
I/O operations in Java
Example
import java.io.*;
public class CopyFile {
public static void main(String args[]) throws IOException {
FileInputStream in = null;
FileOutputStream out = null;
try {
in = new FileInputStream("input.txt");
out = new FileOutputStream("output.txt");
int c;
while ((c = in.read()) != -1) {
out.write(c); }
}finally {
if (in != null) { in.close(); }
if (out != null) { out.close(); } } }}
I/O operations in Java
Character Streams
I/O operations in Java
Example
import java.io.*;
public class CopyFileChar {
public static void main(String args[]) throws IOException {
FileReader in = null;
FileWriter out = null;
try {
in = new FileReader("input.txt");
out = new FileWriter("output.txt");
int c;
while ((c = in.read()) != -1) {
out.write(c); }
}finally {
if (in != null) { in.close(); }
if (out != null) { out.close(); } } }}
I/O operations in Java
 File handling implies reading and writing data to a file.
 The File class from java.io package, allows to work with different formats of files.
 Following operations can be performed on a file:
 Creation of a file
 Get information of a file
 Writing to a file
 Reading from a file
File Handling
I/O operations in Java
File Handling: Useful file Methods
Method Type Description
canRead() Boolean It tests whether the file is readable or not
canWrite() Boolean It tests whether the file is writable or not
createNewFile() Boolean This method creates an empty file
delete() Boolean Deletes a file
exists() Boolean It tests whether the file exists
getName() String Returns the name of the file
getAbsolutePath() String Returns the absolute pathname of the file
length() Long Returns the size of the file in bytes
list() String[] Returns an array of the files in the directory
mkdir() Boolean Creates a directory
I/O operations in Java
import java.io.*;
public class CreateFile {
public static void main(String[] args) {
try {// Creating an object of a file
File myObj = new File("D:FileHandlingNewFilef1.txt");
if (myObj.createNewFile()) {
System.out.println("File created: " + myObj.getName());
} else {
System.out.println("File already exists.")}
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}}}
File Handling: Creation of a file
I/O operations in Java
import java.io.*; // Import the File class
public class FileInformation {
public static void main(String[] args) {
File myObj = new File("NewFilef1.txt");
if (myObj.exists()) {
System.out.println("File name: " + myObj.getName()); // Returning the file name
System.out.println("Absolute path: " + myObj.getAbsolutePath()); // Returning the path of the file
System.out.println("Writeable: " + myObj.canWrite()); // Displaying whether the file is writable
System.out.println("Readable " + myObj.canRead()); // Displaying whether the file is readable or not
System.out.println("File size in bytes " + myObj.length()); // Returning the length of the file in bytes
} else {
System.out.println("The file does not exist.");}}}
File Handling: Get file information
I/O operations in Java
import java.io.*;
public class WriteToFile {
public static void main(String[] args) {
try {
FileWriter myWriter = new FileWriter("D:FileHandlingNewFilef1.txt");
myWriter.write(Java is the prominent programming language of the millenium!"); // Writes this content into the
specified file
myWriter.close(); // Closing is necessary to retrieve the resources allocated
System.out.println("Successfully wrote to the file.");
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();}}}
File Handling: Writing to a file
I/O operations in Java
import java.io.*;
import java.util.Scanner;
public class ReadFromFile {
public static void main(String[] args) {
try {
File myObj = new File("D:FileHandlingNewFilef1.txt"); // Creating an object of the file for reading the data
Scanner myReader = new Scanner(myObj);
while (myReader.hasNextLine()) {
String data = myReader.nextLine();
System.out.println(data);}
myReader.close();
} catch (FileNotFoundException e) {
System.out.println("An error occurred.");
e.printStackTrace();}}}
File Handling: Reading from a file
Multithreaded Programming
 A process of executing multiple threads simultaneously to maximize utilization of CPU.
 A thread is a lightweight sub-process and smallest unit of processing.
 Each thread runs parallel to each other.
 Threads don’t allocate separate memory area; hence it saves memory.
 Context switching between threads takes less time.
Introduction
Multithreaded Programming
 Java provides Thread class to achieve thread programming.
 This class provides methods and constructors to perform operations on a thread and to create it.
 Advantages of Multithread:
 Users are not blocked because threads are independent and multiple operations can be performed
at times.
 The other threads won’t get affected if one thread meets an exception.
Introduction
Multithreaded Programming
 The Java thread states are as
follows:
 New
 Runnable
 Running
 Non-Runnable (blocked/
wait/ sleep)
 Terminated
Life Cycle of a thread
Multithreaded Programming
 It can be defined in the following three sections:
 Thread Priorities
Each thread has a priority which is represented by a number between 1 to 10. Default priority of a
thread is 5 (Normal Priority).
 Synchronization
Capability to control the access of multiple threads to any shared resource.
 Messaging
Threads can communicate each other via messaging. As a thread exits from synchronizing state, it
notifies all the waiting threads.
Java Thread Model
Multithreaded Programming
 A thread can be created by any of the following two ways:
 By extending Thread class
 By implementing Runnable interface
Creation of Thread
Multithreaded Programming
 Commonly used constructors:
 Thread()
 Thread(String name)
 Thread(Runnable r)
 Thread(Runnable r, String name)
 Methods
Creation of Thread: Extending Thread Class
Multithreaded Programming
class MultithreadingDemo extends Thread {
public void run() {
try {
System.out.println ("Thread " + Thread.currentThread().getId() + " is running"); // Displaying the thread that is
running }
catch (Exception e)
{ System.out.println ("Exception is caught"); // Throwing an exception } } }
public class Multithread
{ public static void main(String[] args)
{ int n = 8; // Number of threads
for (int i=0; i<8; i++) {
MultithreadingDemo object = new MultithreadingDemo();
object.start();
} } }
Creation of Thread: Extending Thread Class example
Multithreaded Programming
class MultithreadingDemo implements Runnable {
public void run() {
try {
System.out.println ("Thread " + Thread.currentThread().getId() +" is running"); }
catch (Exception e) {
System.out.println ("Exception is caught"); } } }
class Multithread1 {
public static void main(String[] args) {
int n = 8; // Number of threads
for (int i=0; i<8; i++) {
Thread object = new Thread(new MultithreadingDemo());
object.start(); } } }
Creation of Thread: Implementing Runnable Interface
Multithreaded Programming
 Constants defining priorities of a thread:
 public static int MIN_PRIORITY (1)
 public static int NORM_PRIORITY (5)
 public static int MAX_PRIORITY (10)
Thread Priorities
class TestMultiPriority1 extends Thread{
public void run(){
System.out.println("running thread priority is:"+T
hread.currentThread().getPriority()); }
public static void main(String args[]){
TestMultiPriority1 m1=new TestMultiPriority1();
TestMultiPriority1 m2=new TestMultiPriority1();
m1.setPriority(Thread.MIN_PRIORITY);
m2.setPriority(Thread.MAX_PRIORITY);
m1.start();
m2.start();
} }
Multithreaded Programming
 Capability to control the access of multiple threads to any shared resource.
 Mainly used to prevent thread interference and to prevent consistency problem.
 Two types of thread synchronization:
 Mutual Exclusive
 Synchronized method
 Synchronized block
 Static synchronization
 Cooperation (inter-thread communication)
Thread Synchronization
Multithreaded Programming
 Capability to control the access of multiple threads to any shared resource.
 Mainly used to prevent thread interference and to prevent consistency problem.
 Two types of thread synchronization:
 Mutual Exclusive
 Synchronized method
 Synchronized block
 Static synchronization
 Cooperation (inter-thread communication)
Thread Synchronization
Multithreaded Programming
class Table{
void printTable(int n){//method not synchronized
for(int i=1;i<=5;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
}catch(Exception e){System.out.println(e);}
} } }
class MyThread1 extends Thread{
Table t;
MyThread1(Table t){
this.t=t; }
public void run(){
t.printTable(5); }
Thread Synchronization: Example without synchronization
class MyThread2 extends Thread{
Table t;
MyThread2(Table t){
this.t=t; }
public void run(){
t.printTable(100); } }
class TestSynchronization{
public static void main(String args[]){
Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start(); } }
Multithreaded Programming
class Table{
synchronized void printTable(int n){//method synchronized
for(int i=1;i<=5;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
}catch(Exception e){System.out.println(e);}
} } }
class MyThread1 extends Thread{
Table t;
MyThread1(Table t){
this.t=t; }
public void run(){
t.printTable(5); }
Thread Synchronization: Example with synchronization
class MyThread2 extends Thread{
Table t;
MyThread2(Table t){
this.t=t; }
public void run(){
t.printTable(100); } }
class TestSynchronization{
public static void main(String args[]){
Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start(); } }
Multithreaded Programming
 Deadlock is a situation when no-one is able to complete it’s
processing.
 When a thread is waiting for an object lock that is acquired by
another thread and that thread is waiting for an object lock
that is acquired by the first one.
Deadlock Prevention: Deadlock
Multithreaded Programming
public class TestDeadlockExample1 {
public static void main(String[] args) {
final String resource1 = "ratan jaiswal";
final String resource2 = "vimal jaiswal";
// t1 tries to lock resource1 then resource2
Thread t1 = new Thread() {
public void run() {
synchronized (resource1) {
System.out.println("Thread 1: locked resource 1");
try { Thread.sleep(100);} catch (Exception e) {}
synchronized (resource2) {
System.out.println("Thread 1: locked resource 2");
} } } };
Deadlock Prevention: Deadlock
// t2 tries to lock resource2 then resource1
Thread t2 = new Thread() {
public void run() {
synchronized (resource2) {
System.out.println("Thread 2: locked resource 2");
try { Thread.sleep(100);} catch (Exception e) {}
synchronized (resource1) {
System.out.println("Thread 2: locked resource 1");
} } } };
t1.start();
t2.start();
} }
Multithreaded Programming
 Don’t hold several locks at once. If do, always acquire the locks in same order.
 Avoid nested locks
 Lock only what is required
 Avoid waiting indefinitely.
Deadlock Prevention
Network Programming
 Concept of connecting two or more computing device together so that resources can be shared.
 Java’s .net package is used to implement network programming.
Introduction
Network Programming
 Terminologies:
 IP Address
 Protocol
 Port Number
 MAC Address
 Connection-oriented or connection less protocol
 Socket
Introduction
Network Programming
 Used for communication between the
applications running on different JRE.
 Connection oriented or connection-less.
 Socket and ServerSocket are used for
connection oriented.
 DatagramSocket and DatagramPacket are
used for connection-less.
Java Socket Programming
Network Programming
import java.io.*;
import java.net.*;
public class MyServer {
public static void main(String[] args){
try{
ServerSocket ss=new ServerSocket(6666);
Socket s=ss.accept();//establishes connection
DataInputStream dis=new DataInputStream(s.getInputStream());
String str=(String)dis.readUTF();
System.out.println("message= "+str);
ss.close();
}catch(Exception e){System.out.println(e);} } }
Socket Programming: TCP
import java.io.*;
import java.net.*;
public class MyClient {
public static void main(String[] args) {
try{
Socket s=new Socket("localhost",6666);
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
dout.writeUTF("Hello Server");
dout.flush(); dout.close(); s.close();
}catch(Exception e){System.out.println(e);} } }
Network Programming
import java.net.*;
public class DSender{
public static void main(String[] args) throws Exception {
DatagramSocket ds = new DatagramSocket();
String str = "Welcome java";
InetAddress ip = InetAddress.getByName("127.0.0.1");
DatagramPacket dp = new DatagramPacket(str.getBytes(), str.length(), ip, 3000);
ds.send(dp);
ds.close();
} }
Socket Programming: UDP
import java.net.*;
public class DReceiver{
public static void main(String[] args) throws Exception {
DatagramSocket ds = new DatagramSocket(3000);
byte[] buf = new byte[1024];
DatagramPacket dp = new DatagramPacket(buf, 1024);
ds.receive(dp);
String str = new String(dp.getData(), 0, dp.getLength());
System.out.println(str);
ds.close(); } }
Network Programming
 InetAddress class represents an IP address.
 It provides methods to get the IP of any host name, e.g. www.google.com
 Two types of address types: Unicast and Multicast
 Unicast is an identifier for a single interface whereas Multicast is an identifier for a set of interfaces.
InetAddress
Network Programming
import java.io.*;
import java.net.*;
public class InetDemo{
public static void main(String[] args){
try{
InetAddress ip=InetAddress.getByName("www.google.com");
System.out.println("Host Name: "+ip.getHostName());
System.out.println("IP Address: "+ip.getHostAddress());
}catch(Exception e){System.out.println(e);}
} }
InetAddress
Thank You
Connect on LinkedIn: https://www.linkedin.com/in/aashish-jain-55848216/

Mais conteúdo relacionado

Mais procurados

Mais procurados (20)

JAVA BASICS
JAVA BASICSJAVA BASICS
JAVA BASICS
 
Javascript 101
Javascript 101Javascript 101
Javascript 101
 
Extending the Xbase Typesystem
Extending the Xbase TypesystemExtending the Xbase Typesystem
Extending the Xbase Typesystem
 
Core java
Core javaCore java
Core java
 
Java Basics
Java BasicsJava Basics
Java Basics
 
Javascript Basics
Javascript BasicsJavascript Basics
Javascript Basics
 
Java Tut1
Java Tut1Java Tut1
Java Tut1
 
Recipes to build Code Generators for Non-Xtext Models with Xtend
Recipes to build Code Generators for Non-Xtext Models with XtendRecipes to build Code Generators for Non-Xtext Models with Xtend
Recipes to build Code Generators for Non-Xtext Models with Xtend
 
Java basic
Java basicJava basic
Java basic
 
Basic java for Android Developer
Basic java for Android DeveloperBasic java for Android Developer
Basic java for Android Developer
 
Scala Reflection & Runtime MetaProgramming
Scala Reflection & Runtime MetaProgrammingScala Reflection & Runtime MetaProgramming
Scala Reflection & Runtime MetaProgramming
 
C# Advanced L07-Design Patterns
C# Advanced L07-Design PatternsC# Advanced L07-Design Patterns
C# Advanced L07-Design Patterns
 
Basics of Java
Basics of JavaBasics of Java
Basics of Java
 
Xbase - Implementing Domain-Specific Languages for Java
Xbase - Implementing Domain-Specific Languages for JavaXbase - Implementing Domain-Specific Languages for Java
Xbase - Implementing Domain-Specific Languages for Java
 
Javascript
JavascriptJavascript
Javascript
 
Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to java
 
Code Generation idioms with Xtend
Code Generation idioms with XtendCode Generation idioms with Xtend
Code Generation idioms with Xtend
 
Javascript
JavascriptJavascript
Javascript
 
Intro to Javascript
Intro to JavascriptIntro to Javascript
Intro to Javascript
 

Semelhante a Java

Java basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini indiaJava basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini india
Sanjeev Tripathi
 
Java basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini indiaJava basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini india
sanjeeviniindia1186
 
Java Intro
Java IntroJava Intro
Java Intro
backdoor
 
Java if and else
Java if and elseJava if and else
Java if and else
pratik8897
 

Semelhante a Java (20)

Java basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini indiaJava basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini india
 
Java basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini indiaJava basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini india
 
Java tutorials
Java tutorialsJava tutorials
Java tutorials
 
Java Tutorial | My Heart
Java Tutorial | My HeartJava Tutorial | My Heart
Java Tutorial | My Heart
 
Java Tutorial
Java TutorialJava Tutorial
Java Tutorial
 
Java_Tutorial_Introduction_to_Core_java.ppt
Java_Tutorial_Introduction_to_Core_java.pptJava_Tutorial_Introduction_to_Core_java.ppt
Java_Tutorial_Introduction_to_Core_java.ppt
 
Java tut1
Java tut1Java tut1
Java tut1
 
Java tut1 Coderdojo Cahersiveen
Java tut1 Coderdojo CahersiveenJava tut1 Coderdojo Cahersiveen
Java tut1 Coderdojo Cahersiveen
 
Java tut1
Java tut1Java tut1
Java tut1
 
Javatut1
Javatut1 Javatut1
Javatut1
 
Core Java Tutorials by Mahika Tutorials
Core Java Tutorials by Mahika TutorialsCore Java Tutorials by Mahika Tutorials
Core Java Tutorials by Mahika Tutorials
 
Synapseindia reviews.odp.
Synapseindia reviews.odp.Synapseindia reviews.odp.
Synapseindia reviews.odp.
 
Java Intro
Java IntroJava Intro
Java Intro
 
Computational Problem Solving 016 (1).pptx
Computational Problem Solving 016 (1).pptxComputational Problem Solving 016 (1).pptx
Computational Problem Solving 016 (1).pptx
 
Java tut1
Java tut1Java tut1
Java tut1
 
Tutorial java
Tutorial javaTutorial java
Tutorial java
 
Java tutorial PPT
Java tutorial  PPTJava tutorial  PPT
Java tutorial PPT
 
Unit 1 of java part 2 basic introduction
Unit 1 of java part 2 basic introduction Unit 1 of java part 2 basic introduction
Unit 1 of java part 2 basic introduction
 
Introduction java programming
Introduction java programmingIntroduction java programming
Introduction java programming
 
Java if and else
Java if and elseJava if and else
Java if and else
 

Último

Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak HamilCara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Kandungan 087776558899
 
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort ServiceCall Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Top Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoor
Top Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoorTop Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoor
Top Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoor
dharasingh5698
 

Último (20)

data_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfdata_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdf
 
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
 
Thermal Engineering Unit - I & II . ppt
Thermal Engineering  Unit - I & II . pptThermal Engineering  Unit - I & II . ppt
Thermal Engineering Unit - I & II . ppt
 
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak HamilCara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
 
Unleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leapUnleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leap
 
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort ServiceCall Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
 
Double Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torqueDouble Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torque
 
Generative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTGenerative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPT
 
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...
 
Thermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptThermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.ppt
 
Work-Permit-Receiver-in-Saudi-Aramco.pptx
Work-Permit-Receiver-in-Saudi-Aramco.pptxWork-Permit-Receiver-in-Saudi-Aramco.pptx
Work-Permit-Receiver-in-Saudi-Aramco.pptx
 
KubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlyKubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghly
 
Bhosari ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready For ...
Bhosari ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready For ...Bhosari ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready For ...
Bhosari ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready For ...
 
Top Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoor
Top Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoorTop Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoor
Top Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoor
 
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdfONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
 
NFPA 5000 2024 standard .
NFPA 5000 2024 standard                                  .NFPA 5000 2024 standard                                  .
NFPA 5000 2024 standard .
 
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
 
Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024
 
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
 
Design For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the startDesign For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the start
 

Java

  • 1. Let’s code in Java AASHISH JAIN
  • 2. Session-1  Introduction to Basic Java  Java Fundamentals  Essentials of Object-Oriented Programming  Packages
  • 3. Introduction to Basic Java  Java is a high-level, object-oriented, robust and secure programming language.  James Gosling, Mike Sheridan and Patrick Naughton (popularly known as Green Team) developed Java in 1991.  In the beginning, the language was named as ‘Oak’, but later in 1995, Oak was renamed to Java by Sun microsystems.  Different types of computer applications like standalone applications, web applications, enterprise applications and mobile applications can be developed with the help of Java  According to Sun Microsystems, more than 3 billion devices run Java.
  • 4. Introduction to Basic Java Coding Problems Java Solution Pointers references (“safe” pointers) memory leaks garbage collection error handling exception handling complexity reusable code in APIs platform dependent portable code WHY JAVA? ….plus Security, networking, multithreading, web programming and so on..
  • 5. Features of Java  Architecture neutral  Dynamic  Interpreted  High Performance  Multithreaded  Distributed  Simple  Object-Oriented  Portable  Platform independent  Secured  Robust Introduction to Basic Java
  • 7. Internal detail of JVM Introduction to Basic Java  Class loader loads the class files.  Method area stores pre-class structures as the runtime constant pool.  Heap is the runtime data area in which objects are allocated.  Stack holds local variables and partial results  PC Register contains the address of the JVM instruction currently being executed.  Native method stack contains all the native methods used in the application.
  • 8. A sample Java Program Introduction to Basic Java Source Code Create/Modify Source Code Compile Source Code i.e., javac Welcome.java Bytecode Run Byteode i.e., java Welcome Result If compilation errors If runtime errors or incorrect result public class Welcome { public static void main(String[] args) { System.out.println("Welcome to Java!"); } } … Method Welcome() 0 aload_0 … Method void main(java.lang.String[]) 0 getstatic #2 … 3 ldc #3 <String "Welcome to Java!"> 5 invokevirtual #4 … 8 return Saved on the disk stored on the disk Source code (developed by the programmer) Byte code (generated by the compiler for JVM to read and interpret, not for you to understand)
  • 9. Variables Introduction to Basic Java  A container which holds the value while the java program is executed.  Assigned with a datatype  Combination of vary + able that means it’s value can be changed. class A{ int data=50;//instance variable static int m=100;//static variable void method(){ int n=90;//local variable } } variable Local variable Instance variable Static variable
  • 11. Data types Data Type Default Value Default size boolean false 1 bit char 'u0000' 2 byte byte 0 1 byte short 0 2 byte int 0 4 byte long 0L 8 byte float 0.0f 4 byte double 0.0d 8 byte Java Fundamentals
  • 12. Operators Operator in java is a symbol that is used to perform operations. For example: +, -, *, / etc. There are many types of operators in java which are given below: Java Fundamentals  Unary Operator,  Arithmetic Operator,  Shift Operator,  Relational Operator,  Bitwise Operator,  Logical Operator,  Ternary Operator,  Assignment Operator,
  • 13. Unary Operators Unary operators require only one operand. These are used to perform following operations:  Incrementing/decrementing a value by one  Negating an expression  Inverting the value of a Boolean Java Fundamentals class OperatorExample{ public static void main(String args[]){ i nt x=10, a=10; boolean c=true; System.out.println(x++);//10 (11) System.out.println(++x);//12 System.out.println(x--);//12 (11) System.out.println(--x);//10 System.out.println(~a);//-11 System.out.println(!c);//false }}
  • 14. Arithmetic Operators Arithmetic operators are used to perform basic math operations like addition, subtraction etc. Java Fundamentals class OperatorExample{ public static void main(String args[]){in t a=10; int b=5; System.out.println(a+b);//15 System.out.println(a-b);//5 System.out.println(a*b);//50 System.out.println(a/b);//2 System.out.println(a%b);//0 }}
  • 15. Shift Operators Shift operators are used to perform following operations:  << (left shift)  >> (signed right shift)  >>> (unsigned right shift) Java Fundamentals class OperatorExample{ public static void main(String args[]){ System.out.println(10<<2);//10*2^2=10*4=40 System.out.println(10<<3);//10*2^3=10*8=80 System.out.println(10>>2);//10/2^2=10/4=2 System.out.println(20>>2);//20/2^2=20/4=5 System.out.println(20>>>2); //5 System.out.println(-20>>>2); //1073741819 }}
  • 16. Relational Operators Relational operators are used for comparisons:  <= (less than equal to)  >= (greater than equal to)  == (equals to)  != (not equal to)  < (less than)  > (greater than)  instanceof Java Fundamentals class OperatorExample{ public static void main(String args[]){in t a=10; int b=5; System.out.println(a>b);//true System.out.println(a<b);//false System.out.println(a==b);//false System.out.println(a!=b);//true System.out.println(a>=b);//true }}
  • 17. Bitwise Operators  | (Bitwise OR)  & (Bitwise AND) Java Fundamentals class OperatorExample{ public static void main(String args[]) {int a=2; int b=3; System.out.println(a&b);//0010 & 001100102 System.out.println(a|b);// 0010 | 001100113 }}
  • 18. Logical Operators  && (Logical AND)  || (Logical OR) Java Fundamentals class OperatorExample{ public static void main(String args[]) {int a=10; int b=5; System.out.println(a>b && a<b);//false System.out.println(a>b || a<b);//true }}
  • 19. Ternary Operator Ternary Operator is used as one liner replacement for if-then-else statement. (condition)?(this block will execute in case of true):(this block will execute in case of false) Java Fundamentals class OperatorExample{ public static void main(String args[]) {int a=10; int b=5; Int c=a>b?a:b; System.out.println(c);//10 }}
  • 20. Assignment Operators Assignment operators are used to assign the value on it’s right to the operand on it’s left. Java Fundamentals class OperatorExample{ public static void main(String args[]){in t a=10; a+=3;//10+3 System.out.println(a); a-=4;//13-4 System.out.println(a); a*=2;//9*2 System.out.println(a); a/=2;//18/2 System.out.println(a); }}
  • 21. Control Statements  if statement  if-else statement  nested if statement  if-else-if ladder  Switch statement  For Loop  While Loop  Do-while Loop Java Fundamentals
  • 22. if Statement if(condition){ //code to be executed } Java Fundamentals public class IfExample { public static void main(String[] args) { //defining an 'age' variable int age=20; //checking the age if(age>18){ System.out.print("Age is greater than 18"); } } }
  • 23. If-else Statement if(condition){ //code if condition is true }else{ //code if condition is false } Java Fundamentals public class IfElseExample { public static void main(String[] args) { //defining a variable int number=13; //Check if the number is divisible by 2 or not if(number%2==0){ System.out.println("even number"); }else{ System.out.println("odd number"); } } }
  • 24. Nested if Statement if(condition){ //code to be executed if(condition){ //code to be executed } } Java Fundamentals public class JavaNestedIfExample { public static void main(String[] args) { //Creating two variables for age and weight int age=20; int weight=80; //applying condition on age and weight if(age>=18){ if(weight>50){ System.out.println("You are eligible to don ate blood"); } } }}
  • 25. If-else-if Ladder if(condition1){ //code to be executed if condition1 is true }else if(condition2){ //code to be executed if condition2 is true } else if(condition3){ //code to be executed if condition3 is true} ... else{ //code to be executed if all the conditions are false} Java Fundamentals public class IfElseIfExample { public static void main(String[] args) { int marks=65; if(marks<50){ System.out.println("fail"); } else if(marks>=50 && marks<60){ System.out.println("D grade"); } else if(marks>=60 && marks<70){ System.out.println("C grade"); } else if(marks>=70 && marks<80){ System.out.println("B grade"); } else if(marks>=80 && marks<90){ System.out.println("A grade"); } else if(marks>=90 && marks<100){ System.out.println("A+ grade"); } else{ System.out.println("Invalid!"); } } }
  • 26. Switch Statement switch(expression){ case value1: //code to be executed; break; //optional case value2: //code to be executed; break; //optional ...... default: code to be executed if all cases are not matched;} Java Fundamentals public class SwitchExample { public static void main(String[] args) { //Declaring a variable for switch expression int number=20; //Switch expression switch(number){ case 10: System.out.println("10"); break; case 20: System.out.println("20"); break; case 30: System.out.println("30"); break; //Default case statement default: System.out.println("Not in 10, 20 or 30"); } } }
  • 27. For Loop for(initialization;condition;incr/decr){ //statement or code to be executed } NOTE: If the number of iteration is fixed, it is recommended to use for loop. Java Fundamentals public class ForExample { public static void main(String[] args) { //Code of Java for loop for(int i=1;i<=10;i++){ System.out.println(i); } } }
  • 28. while Loop while(condition){ //code to be executed } NOTE: If the number of iteration is not fixed, it is recommended to use this loop. Java Fundamentals public class WhileExample { public static void main(String[] args) { int i=1; while(i<=10){ System.out.println(i); i++; } } }
  • 29. Do-while Loop do{ //code to be executed }while(condition); NOTE: If the number of iteration is not fixed and the loop must have to be executed at least once, it is recommended to use this loop. Java Fundamentals public class DoWhileExample { public static void main(String[] args) { int i=1; do{ System.out.println(i); i++; }while(i<=10); } }
  • 30. Break statement Java Fundamentals public class BreakExample { public static void main(String[] args) { //using for loop for(int i=1;i<=10;i++){ if(i==5){ //breaking the loop break; } System.out.println(i); } } }
  • 31. continue statement Java Fundamentals public class ContinueExample { public static void main(String[] args) { //for loop for(int i=1;i<=10;i++){ if(i==5){ //using continue statement continue;//it will skip the rest statement within this block } System.out.println(i); } } }
  • 32. Arrays Java Fundamentals  An object which contains elements of a similar data type.  Elements are stored in contiguous memory location.  Only fixed number of elements can be stored.
  • 33. Arrays Java Fundamentals  Two types:  Single Dimension Array  Multidimensional Array  Declaration:  dataType[] arr; (or)  dataType []arr; (or)  dataType arr[];  Instantiation:  arrayRefVar=new datatype[size];
  • 34. String Java Fundamentals  String is basically an object that represents sequence of character values.  String in Java is immutable which means it cannot be changed. Whenever we change any string, a new instance is created.  The java.lang.String class is used to create a string object.  Two ways to create String object:  By String literal  By new Keyword
  • 35. By String literals Java Fundamentals  Created by using double quotes.  String str=“Welcome”;  Each time you create a string literal, JVM checks the “String constant pool” first.  If it already exists, a reference to the pooled instance is returned.  If not, a new string instance is created and placed in the pool. For example:  String s1=“Welcome”;  String s2=“Welcome”;
  • 36. By new keyword Java Fundamentals  String s=new String("Welcome");//creates two objects and one reference variable  In such case, JVM will create a new string object in normal (non-pool) heap memory.  The literal "Welcome" will be placed in the string constant pool.  s will refer to the object in a heap (non-pool).
  • 37. Operations on String Java Fundamentals public class StringExample{ public static void main(String args[]){ String str1=“Learn To Code"; String str2=“Java Programming"; System.out.println(str1.charAt(4));//prints the char value at the 4th index System.out.println(str1.concat(str2));//concatenating one string System.out.println(str1.compareTo(str2));//1 System.out.println(str1.contains(“To”));//true System.out.println(str1.equals(str2));//false System.out.println(str1.equalsIgnoreCase(str2));//false System.out.println(str1.length());//13 }}
  • 38. Enumerations (Enum) Java Fundamentals  The Enum is a data type which contains a fixed set of constants.  Static and final implicitly. class EnumExample{ //defining the enum inside the class public enum Season { WINTER, SPRING, SUMMER, FALL } public static void main(String[] args) { //traversing the enum for (Season s : Season.values()) System.out.println(s); }}
  • 39. Object and Class Essentials of Object-Oriented Programming  An object is the physical as well as logical entity, whereas, a class is a logical entity only.  An entity that has state (data/ value) and behaviour (functionality) is known as object.  A class is a template or blueprint from which objects are created.
  • 41. Naming convention Essentials of Object-Oriented Programming  A class/interface should start with uppercase letter e.g. Student, College, University etc.  Class should be a noun and interface should be an adjective.  A method should start with lowercase letter and/or followed by an uppercase letter e.g. draw(), actionPerformed() etc.  A variable should start with lowercase letter e.g. id, name, rollNo, etc.  A package name should be in lowercase letter such as lang, io, net, etc.  A constant should be in uppercase letters such as SUNDAY, MONDAY etc.
  • 42. Class fundamentals Essentials of Object-Oriented Programming //Defining a Student class. class Student{ //defining fields int id; //field or data member or instance variable String name; //creating main method inside the Student class public static void main(String args[]){ //Creating an object or instance Student s1=new Student(); //creating an object of Student //Printing values of the object System.out.println(s1.id); //accessing member through reference variable System.out.println(s1.name); } }
  • 43. Class fundamentals Essentials of Object-Oriented Programming  There are three ways to initialize object:  By reference variable  By method  By constructor
  • 44. Class fundamentals: By reference variables Essentials of Object-Oriented Programming class Student{ int id; String name; } class TestStudent{ public static void main(String args[]){ Student s1=new Student(); s1.id=101; s1.name="Sonoo"; System.out.println(s1.id+" "+s1.name);//printing members with a white space } }
  • 45. Class fundamentals: By method Essentials of Object-Oriented Programming class Student{ int rollno; String name; void insertRecord(int r, String n){ rollno=r; name=n; } void displayInformation() {System.out.println(rollno+" "+name);} } class TestStudent{ public static void main(String args[]){ Student s1=new Student(); Student s2=new Student(); s1.insertRecord(101,“Abhishek"); s2.insertRecord(202,"Anchit"); s1.displayInformation(); s2.displayInformation(); } }
  • 46. Class fundamentals: By constructor Essentials of Object-Oriented Programming  A special type of method used to initialize the object.  Constructor name must be same as its class name.  It must have no explicit return type.  It can not be abstract, static, final and synchronized.  It can be of two types: default and parameterized
  • 47. Class fundamentals: By constructor Essentials of Object-Oriented Programming class Student{ int id; String name; //creating a parameterized constructor Student(int i,String n){ id = i; name = n; } //method to display the values void display(){System.out.println(id+" "+name);} public static void main(String args[]){ //creating objects and passing values Student4 s1 = new Student4(111,"Karan"); Student4 s2 = new Student4(222,"Aryan"); //calling method to display the values of object s1.display(); s2.display(); } }
  • 48. Static keyword Essentials of Object-Oriented Programming  Used for memory management mainly.  Can be applied with variables, methods, blocks and nested classes.
  • 49. this keyword Essentials of Object-Oriented Programming  Can be used to refer current class instance variable.  Can be used to invoke current class methods.  this() can be used to invoke current class constructor. class A{ void m(){System.out.println("hello m");} void n(){ System.out.println("hello n"); //m(); //same as this.m() this.m(); } } class TestThis{ public static void main(String args[]){ A a=new A(); a.n(); }}
  • 50. final keyword Essentials of Object-Oriented Programming  Used to restrict the user.  Can be applied to variable, method, and class. class Bike{ final int speedlimit=90;//final variable void run(){ speedlimit=400; } public static void main(String args[]){ Bike obj=new Bike (); obj.run(); } }
  • 51. super keyword Essentials of Object-Oriented Programming  Used to refer immediate parent class object. class Animal{ String color="white"; } class Dog extends Animal{ String color="black"; void printColor(){ System.out.println(color); //prints color of Dog class System.out.println(super.color); //prints color of Animal class } } class TestSuper{ public static void main(String args[]){ Dog d=new Dog(); d.printColor(); }}
  • 52. Polymorphism Essentials of Object-Oriented Programming  It is a concept to perform a single action in different ways.  Derived from Greek words: poly and morphs which means many and forms respectively.  Two types:  Compile-time polymorphism (Overloading)  Run-Time polymorphism (Overriding)
  • 53. Method Overloading Essentials of Object-Oriented Programming  A class has multiple methods having same name but different in parameters, called as Method Overloading. class Adder{ static int add(int a,int b){return a+b;} static int add(int a,int b,int c){return a+b+c;} } class TestOverloading1{ public static void main(String[] args){ System.out.println(Adder.add(11,11)); System.out.println(Adder.add(11,11,11)); }}
  • 54. Method Overriding Essentials of Object-Oriented Programming  If a subclass provides the specific implementation of the method that has been declared by one of its parent class, known as method overriding. class Vehicle{ void run(){System.out.println("Vehicle is running");} } //Creating a child class class Bike extends Vehicle{ public static void main(String args[]){ //creating an instance of child class Bike obj = new Bike(); //calling the method with child class instance obj.run(); } }
  • 55. Abstraction: Abstract class Essentials of Object-Oriented Programming  Abstraction is a process of hiding the implementation details and showing only functionality to the user.  A class declared with abstract keyword is known as abstract class.  It can have abstract and non-abstract methods.
  • 56. Abstraction: Abstract class Essentials of Object-Oriented Programming abstract class Bike{ abstract void run(); } class Honda extends Bike{ void run(){System.out.println("running safely"); } public static void main(String args[]){ Bike obj = new Honda4(); obj.run(); } }
  • 57. Abstraction: Interface Essentials of Object-Oriented Programming  An interface is a blueprint of class.  It has static constants and abstract methods.  Represents IS-A relationship.  Used to achieve abstraction, to support functionality of multiple inheritance, and to achieve loose coupling.  A class uses implements keyword to implement an interface. interface printable{ void print(); } class Example implements printable{ pu blic void print(){ System.out.println("Hello");} public static void main(String args[]){ Exa mple obj = new Example(); obj.print(); } }
  • 58. Abstraction: Abstract class V/S Interface Essentials of Object-Oriented Programming Abstract class Interface Can have abstract and non-abstract methods Can have only abstract methods Doesn’t support multiple inheritance Supports multiple inheritance Can have static, non-static, final, and non-final variables Can have only static and final variables Can provide the implementation of an interface Can’t provide the implementation of abstract class Can extend multiple interfaces and an abstract Can extend interfaces only Extended using keyword “extends” Implemented using keyword “implements”
  • 59. What is a package? Packages  A group of similar types of classes, interfaces and sub-packages.  Categorized into two forms:  Built-in packages  User-defined packages
  • 60. Why packages? Packages  To categorize classes and interfaces for easily maintenance.  Provides access protection.  Removes naming collision.
  • 61. Create a package Packages  The package keyword is used to create a package in java.  If no using an IDE, follow the syntax:  javac –d directory javafilename, for e.g.:  javac –d . Simple.java  -d specifies the destination where to put the generated class file,  To keep the package within the same directory, use . (dot)  To compile: javac –d . Simple.Java  To run: java mypack.Simple package mypack; public class Simple{ public static void main(String args[]){ System.out.println("Welcome to package"); } }
  • 62. Access a package Packages  Following are the ways to access the package from outside the package:  import package.*;  import package.classname;  Fully qualified name package pack; public class A{ public void msg(){System.out.println("Hello");} } package mypack; import pack.*; class B{ public static void main(String args[]){ A obj = new A(); obj.msg(); } }
  • 63. Understanding class path Packages  To compile:  e:sources> javac -d c:classes A.java  To run the program from e:sources:  e:sources> set classpath=c:classes;.;  e:sources> java mypack.A  Another way to run this program:  e:sources> java -classpath c:classes mypack.A  -classpath switch temporary loads the class file while it can be done permanent by setting classpath in environment variable. package mypack; public class A{ public static void main(String args[]){ System.out.println("Welcome to package"); } }
  • 64. Access modifiers and their scope Packages Access Modifiers Within class Within same package Within subclass of other package Within class of other package public Yes Yes Yes Yes protected Yes Yes Yes No default Yes Yes No No private Yes No No No
  • 65. Session-2  Exception Handling  I/O operations in Java  Multithreaded Programming  Network Programming
  • 66. Exception Handling  One of the powerful mechanism to handle the runtime errors so that normal flow of application can be maintained.  Three types of exceptions:  Checked Exception  Unchecked Exception  Error
  • 69. Exception Keywords Exception Handling  try: used to specify a block where exception code is placed. The try block must be followed by either catch or finally block.  catch: used to handle the exception. Must be preceded by try block and can be followed by finally block.  finally: used to execute the important code of the program. This block will always be executed irrespective of the exception handled or not.  throw: used to throw an exception.  throws: used to declare exceptions. It doesn’t throw an exception rather it specifies an exception may occur in this method. public class JavaExceptionExample{ public static void main(String args[]){ try{ //code that may raise exception int data=100/0; }catch(ArithmeticException e){System.out.println(e);} //rest code of the program System.out.println("rest of the code..."); } }
  • 70. Exception Handling public class TestThrow{ static void validate(int age){ if(age<18) throw new ArithmeticException(“Age is not valid"); else System.out.println("welcome to vote"); } public static void main(String args[]){ validate(13); System.out.println("rest of the code..."); } } Usage of throw keyword
  • 71. Exception Handling import java.io.*; class M{ void method()throws IOException{ System.out.println("device operation performed"); } } class Testthrows{ public static void main(String args[])throws IOException{//declare exception M m=new M(); m.method(); System.out.println("normal flow..."); }} Usage of throws keyword
  • 72. Exception Handling class TestFinallyBlock{ public static void main(String args[]){ try{ int data=25/5; System.out.println(data); } catch(NullPointerException e){System.out.println(e);} finally{System.out.println("finally block is always executed");} System.out.println("rest of the code..."); } } Usage of finally keyword
  • 73. Exception Handling class InvalidAgeException extends Exception{ InvalidAgeException(String s){ super(s); } } User Defined Exception class TestCustomException1{ static void validate(int age)throws InvalidAgeException{ if(age<18) throw new InvalidAgeException(“Age is not valid"); else System.out.println("welcome to vote"); } public static void main(String args[]){ try{ validate(13); } catch(Exception m) { System.out.println("Exception occured: "+m);} System.out.println("rest of the code..."); }}
  • 74. I/O operations in Java  Java I/O (input/output) is used to process the input and produce the output.  Java uses concept of streams to make I/O operations fast.  The java.io package contains all the classes required for input and output operations.  There are two types of streams which are further categorized into input and output streams:  Byte Streams  Character Streams
  • 75. I/O operations in Java Byte Streams
  • 76. I/O operations in Java Example import java.io.*; public class CopyFile { public static void main(String args[]) throws IOException { FileInputStream in = null; FileOutputStream out = null; try { in = new FileInputStream("input.txt"); out = new FileOutputStream("output.txt"); int c; while ((c = in.read()) != -1) { out.write(c); } }finally { if (in != null) { in.close(); } if (out != null) { out.close(); } } }}
  • 77. I/O operations in Java Character Streams
  • 78. I/O operations in Java Example import java.io.*; public class CopyFileChar { public static void main(String args[]) throws IOException { FileReader in = null; FileWriter out = null; try { in = new FileReader("input.txt"); out = new FileWriter("output.txt"); int c; while ((c = in.read()) != -1) { out.write(c); } }finally { if (in != null) { in.close(); } if (out != null) { out.close(); } } }}
  • 79. I/O operations in Java  File handling implies reading and writing data to a file.  The File class from java.io package, allows to work with different formats of files.  Following operations can be performed on a file:  Creation of a file  Get information of a file  Writing to a file  Reading from a file File Handling
  • 80. I/O operations in Java File Handling: Useful file Methods Method Type Description canRead() Boolean It tests whether the file is readable or not canWrite() Boolean It tests whether the file is writable or not createNewFile() Boolean This method creates an empty file delete() Boolean Deletes a file exists() Boolean It tests whether the file exists getName() String Returns the name of the file getAbsolutePath() String Returns the absolute pathname of the file length() Long Returns the size of the file in bytes list() String[] Returns an array of the files in the directory mkdir() Boolean Creates a directory
  • 81. I/O operations in Java import java.io.*; public class CreateFile { public static void main(String[] args) { try {// Creating an object of a file File myObj = new File("D:FileHandlingNewFilef1.txt"); if (myObj.createNewFile()) { System.out.println("File created: " + myObj.getName()); } else { System.out.println("File already exists.")} } catch (IOException e) { System.out.println("An error occurred."); e.printStackTrace(); }}} File Handling: Creation of a file
  • 82. I/O operations in Java import java.io.*; // Import the File class public class FileInformation { public static void main(String[] args) { File myObj = new File("NewFilef1.txt"); if (myObj.exists()) { System.out.println("File name: " + myObj.getName()); // Returning the file name System.out.println("Absolute path: " + myObj.getAbsolutePath()); // Returning the path of the file System.out.println("Writeable: " + myObj.canWrite()); // Displaying whether the file is writable System.out.println("Readable " + myObj.canRead()); // Displaying whether the file is readable or not System.out.println("File size in bytes " + myObj.length()); // Returning the length of the file in bytes } else { System.out.println("The file does not exist.");}}} File Handling: Get file information
  • 83. I/O operations in Java import java.io.*; public class WriteToFile { public static void main(String[] args) { try { FileWriter myWriter = new FileWriter("D:FileHandlingNewFilef1.txt"); myWriter.write(Java is the prominent programming language of the millenium!"); // Writes this content into the specified file myWriter.close(); // Closing is necessary to retrieve the resources allocated System.out.println("Successfully wrote to the file."); } catch (IOException e) { System.out.println("An error occurred."); e.printStackTrace();}}} File Handling: Writing to a file
  • 84. I/O operations in Java import java.io.*; import java.util.Scanner; public class ReadFromFile { public static void main(String[] args) { try { File myObj = new File("D:FileHandlingNewFilef1.txt"); // Creating an object of the file for reading the data Scanner myReader = new Scanner(myObj); while (myReader.hasNextLine()) { String data = myReader.nextLine(); System.out.println(data);} myReader.close(); } catch (FileNotFoundException e) { System.out.println("An error occurred."); e.printStackTrace();}}} File Handling: Reading from a file
  • 85. Multithreaded Programming  A process of executing multiple threads simultaneously to maximize utilization of CPU.  A thread is a lightweight sub-process and smallest unit of processing.  Each thread runs parallel to each other.  Threads don’t allocate separate memory area; hence it saves memory.  Context switching between threads takes less time. Introduction
  • 86. Multithreaded Programming  Java provides Thread class to achieve thread programming.  This class provides methods and constructors to perform operations on a thread and to create it.  Advantages of Multithread:  Users are not blocked because threads are independent and multiple operations can be performed at times.  The other threads won’t get affected if one thread meets an exception. Introduction
  • 87. Multithreaded Programming  The Java thread states are as follows:  New  Runnable  Running  Non-Runnable (blocked/ wait/ sleep)  Terminated Life Cycle of a thread
  • 88. Multithreaded Programming  It can be defined in the following three sections:  Thread Priorities Each thread has a priority which is represented by a number between 1 to 10. Default priority of a thread is 5 (Normal Priority).  Synchronization Capability to control the access of multiple threads to any shared resource.  Messaging Threads can communicate each other via messaging. As a thread exits from synchronizing state, it notifies all the waiting threads. Java Thread Model
  • 89. Multithreaded Programming  A thread can be created by any of the following two ways:  By extending Thread class  By implementing Runnable interface Creation of Thread
  • 90. Multithreaded Programming  Commonly used constructors:  Thread()  Thread(String name)  Thread(Runnable r)  Thread(Runnable r, String name)  Methods Creation of Thread: Extending Thread Class
  • 91. Multithreaded Programming class MultithreadingDemo extends Thread { public void run() { try { System.out.println ("Thread " + Thread.currentThread().getId() + " is running"); // Displaying the thread that is running } catch (Exception e) { System.out.println ("Exception is caught"); // Throwing an exception } } } public class Multithread { public static void main(String[] args) { int n = 8; // Number of threads for (int i=0; i<8; i++) { MultithreadingDemo object = new MultithreadingDemo(); object.start(); } } } Creation of Thread: Extending Thread Class example
  • 92. Multithreaded Programming class MultithreadingDemo implements Runnable { public void run() { try { System.out.println ("Thread " + Thread.currentThread().getId() +" is running"); } catch (Exception e) { System.out.println ("Exception is caught"); } } } class Multithread1 { public static void main(String[] args) { int n = 8; // Number of threads for (int i=0; i<8; i++) { Thread object = new Thread(new MultithreadingDemo()); object.start(); } } } Creation of Thread: Implementing Runnable Interface
  • 93. Multithreaded Programming  Constants defining priorities of a thread:  public static int MIN_PRIORITY (1)  public static int NORM_PRIORITY (5)  public static int MAX_PRIORITY (10) Thread Priorities class TestMultiPriority1 extends Thread{ public void run(){ System.out.println("running thread priority is:"+T hread.currentThread().getPriority()); } public static void main(String args[]){ TestMultiPriority1 m1=new TestMultiPriority1(); TestMultiPriority1 m2=new TestMultiPriority1(); m1.setPriority(Thread.MIN_PRIORITY); m2.setPriority(Thread.MAX_PRIORITY); m1.start(); m2.start(); } }
  • 94. Multithreaded Programming  Capability to control the access of multiple threads to any shared resource.  Mainly used to prevent thread interference and to prevent consistency problem.  Two types of thread synchronization:  Mutual Exclusive  Synchronized method  Synchronized block  Static synchronization  Cooperation (inter-thread communication) Thread Synchronization
  • 95. Multithreaded Programming  Capability to control the access of multiple threads to any shared resource.  Mainly used to prevent thread interference and to prevent consistency problem.  Two types of thread synchronization:  Mutual Exclusive  Synchronized method  Synchronized block  Static synchronization  Cooperation (inter-thread communication) Thread Synchronization
  • 96. Multithreaded Programming class Table{ void printTable(int n){//method not synchronized for(int i=1;i<=5;i++){ System.out.println(n*i); try{ Thread.sleep(400); }catch(Exception e){System.out.println(e);} } } } class MyThread1 extends Thread{ Table t; MyThread1(Table t){ this.t=t; } public void run(){ t.printTable(5); } Thread Synchronization: Example without synchronization class MyThread2 extends Thread{ Table t; MyThread2(Table t){ this.t=t; } public void run(){ t.printTable(100); } } class TestSynchronization{ public static void main(String args[]){ Table obj = new Table();//only one object MyThread1 t1=new MyThread1(obj); MyThread2 t2=new MyThread2(obj); t1.start(); t2.start(); } }
  • 97. Multithreaded Programming class Table{ synchronized void printTable(int n){//method synchronized for(int i=1;i<=5;i++){ System.out.println(n*i); try{ Thread.sleep(400); }catch(Exception e){System.out.println(e);} } } } class MyThread1 extends Thread{ Table t; MyThread1(Table t){ this.t=t; } public void run(){ t.printTable(5); } Thread Synchronization: Example with synchronization class MyThread2 extends Thread{ Table t; MyThread2(Table t){ this.t=t; } public void run(){ t.printTable(100); } } class TestSynchronization{ public static void main(String args[]){ Table obj = new Table();//only one object MyThread1 t1=new MyThread1(obj); MyThread2 t2=new MyThread2(obj); t1.start(); t2.start(); } }
  • 98. Multithreaded Programming  Deadlock is a situation when no-one is able to complete it’s processing.  When a thread is waiting for an object lock that is acquired by another thread and that thread is waiting for an object lock that is acquired by the first one. Deadlock Prevention: Deadlock
  • 99. Multithreaded Programming public class TestDeadlockExample1 { public static void main(String[] args) { final String resource1 = "ratan jaiswal"; final String resource2 = "vimal jaiswal"; // t1 tries to lock resource1 then resource2 Thread t1 = new Thread() { public void run() { synchronized (resource1) { System.out.println("Thread 1: locked resource 1"); try { Thread.sleep(100);} catch (Exception e) {} synchronized (resource2) { System.out.println("Thread 1: locked resource 2"); } } } }; Deadlock Prevention: Deadlock // t2 tries to lock resource2 then resource1 Thread t2 = new Thread() { public void run() { synchronized (resource2) { System.out.println("Thread 2: locked resource 2"); try { Thread.sleep(100);} catch (Exception e) {} synchronized (resource1) { System.out.println("Thread 2: locked resource 1"); } } } }; t1.start(); t2.start(); } }
  • 100. Multithreaded Programming  Don’t hold several locks at once. If do, always acquire the locks in same order.  Avoid nested locks  Lock only what is required  Avoid waiting indefinitely. Deadlock Prevention
  • 101. Network Programming  Concept of connecting two or more computing device together so that resources can be shared.  Java’s .net package is used to implement network programming. Introduction
  • 102. Network Programming  Terminologies:  IP Address  Protocol  Port Number  MAC Address  Connection-oriented or connection less protocol  Socket Introduction
  • 103. Network Programming  Used for communication between the applications running on different JRE.  Connection oriented or connection-less.  Socket and ServerSocket are used for connection oriented.  DatagramSocket and DatagramPacket are used for connection-less. Java Socket Programming
  • 104. Network Programming import java.io.*; import java.net.*; public class MyServer { public static void main(String[] args){ try{ ServerSocket ss=new ServerSocket(6666); Socket s=ss.accept();//establishes connection DataInputStream dis=new DataInputStream(s.getInputStream()); String str=(String)dis.readUTF(); System.out.println("message= "+str); ss.close(); }catch(Exception e){System.out.println(e);} } } Socket Programming: TCP import java.io.*; import java.net.*; public class MyClient { public static void main(String[] args) { try{ Socket s=new Socket("localhost",6666); DataOutputStream dout=new DataOutputStream(s.getOutputStream()); dout.writeUTF("Hello Server"); dout.flush(); dout.close(); s.close(); }catch(Exception e){System.out.println(e);} } }
  • 105. Network Programming import java.net.*; public class DSender{ public static void main(String[] args) throws Exception { DatagramSocket ds = new DatagramSocket(); String str = "Welcome java"; InetAddress ip = InetAddress.getByName("127.0.0.1"); DatagramPacket dp = new DatagramPacket(str.getBytes(), str.length(), ip, 3000); ds.send(dp); ds.close(); } } Socket Programming: UDP import java.net.*; public class DReceiver{ public static void main(String[] args) throws Exception { DatagramSocket ds = new DatagramSocket(3000); byte[] buf = new byte[1024]; DatagramPacket dp = new DatagramPacket(buf, 1024); ds.receive(dp); String str = new String(dp.getData(), 0, dp.getLength()); System.out.println(str); ds.close(); } }
  • 106. Network Programming  InetAddress class represents an IP address.  It provides methods to get the IP of any host name, e.g. www.google.com  Two types of address types: Unicast and Multicast  Unicast is an identifier for a single interface whereas Multicast is an identifier for a set of interfaces. InetAddress
  • 107. Network Programming import java.io.*; import java.net.*; public class InetDemo{ public static void main(String[] args){ try{ InetAddress ip=InetAddress.getByName("www.google.com"); System.out.println("Host Name: "+ip.getHostName()); System.out.println("IP Address: "+ip.getHostAddress()); }catch(Exception e){System.out.println(e);} } } InetAddress
  • 108. Thank You Connect on LinkedIn: https://www.linkedin.com/in/aashish-jain-55848216/

Notas do Editor

  1. Hello this is my note
  2. Simple: Java is partially modeled on C++, but greatly simplified and improved. Some people refer to Java as "C++--" because it is like C++ but with more functionality and fewer negative aspects. Object Oriented: Java is inherently object-oriented. Although many object-oriented languages began strictly as procedural languages, Java was designed from the start to be object-oriented. Object-oriented programming (OOP) is a popular programming approach that is replacing traditional procedural programming techniques. Portable: Java programs are portable. They can be run on any platform without being recompiled. Secured: Java implements several security mechanisms to protect your system against harm caused by stray programs. Robust: Java compilers can detect many problems that would first show up at execution time in other languages. Java has eliminated certain types of error-prone programming constructs found in other languages. Java has a runtime exception-handling feature to provide programming support for robustness Architecture-Neutral: Write once, run anywhere. With a Java Virtual Machine (JVM), you can write one program that will run on any platform. Dynamic: Java was designed to adapt to an evolving environment. New code can be loaded on the fly without recompilation. There is no need for developers to create, and for users to install, major new software versions. New features can be incorporated transparently as needed. Interpreted: You need an interpreter to run Java programs. The programs are compiled into the Java Virtual Machine code called bytecode. The bytecode is machine-independent and can run on any machine that has a Java interpreter, which is part of the Java Virtual Machine (JVM). Multithreaded: Multithread programming is smoothly integrated in Java, whereas in other languages you have to call procedures specific to the operating system to enable multithreading. Distributed: Distributed computing involves several computers working together on a network. Java is designed to make distributed computing easy. Since networking capability is inherently integrated into Java, writing network programs is like sending and receiving data to and from a file.
  3. https://j4school.wordpress.com/java-tutorials/core-java/introduction-to-java/java-magic-bytecode-java-virtual-machine-jit-jre-jdk/
  4. To solve these problems, a new language standard was developed i.e. Unicode System.In unicode, character holds 2 byte, so java also uses 2 byte for characters.lowest value:\u0000highest value:\uFFFF
  5. Hello this is my note