Se ha denunciado esta presentación.
Se está descargando tu SlideShare. ×
Anuncio
Anuncio
Anuncio
Anuncio
Anuncio
Anuncio
Anuncio
Anuncio
Anuncio
Anuncio
Anuncio
Anuncio
Cargando en…3
×

Eche un vistazo a continuación

1 de 108 Anuncio

This has been presented in association with Robosepians for Java concepts. Basic concepts of Java including features, conditional statements, loop statements, arrays, string, primitive datatypes, essentials of Java including oops concepts, classes, objects, polymorphism, advance topics including packages, exception handling, multihtreading and network programming have been discussed.

This has been presented in association with Robosepians for Java concepts. Basic concepts of Java including features, conditional statements, loop statements, arrays, string, primitive datatypes, essentials of Java including oops concepts, classes, objects, polymorphism, advance topics including packages, exception handling, multihtreading and network programming have been discussed.

Anuncio
Anuncio

Más Contenido Relacionado

Presentaciones para usted (20)

Similares a Java (20)

Anuncio

Más reciente (20)

Java

  1. 1. Let’s code in Java AASHISH JAIN
  2. 2. Session-1  Introduction to Basic Java  Java Fundamentals  Essentials of Object-Oriented Programming  Packages
  3. 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. 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. 5. Features of Java  Architecture neutral  Dynamic  Interpreted  High Performance  Multithreaded  Distributed  Simple  Object-Oriented  Portable  Platform independent  Secured  Robust Introduction to Basic Java
  6. 6. JDK, JRE, JVM Introduction to Basic Java
  7. 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. 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. 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
  10. 10. Java Fundamentals Data types
  11. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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.
  40. 40. Inheritance Essentials of Object-Oriented Programming
  41. 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. 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. 43. Class fundamentals Essentials of Object-Oriented Programming  There are three ways to initialize object:  By reference variable  By method  By constructor
  44. 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. 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. 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. 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. 48. Static keyword Essentials of Object-Oriented Programming  Used for memory management mainly.  Can be applied with variables, methods, blocks and nested classes.
  49. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 60. Why packages? Packages  To categorize classes and interfaces for easily maintenance.  Provides access protection.  Removes naming collision.
  61. 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. 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. 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. 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. 65. Session-2  Exception Handling  I/O operations in Java  Multithreaded Programming  Network Programming
  66. 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
  67. 67. Exception Propagation Exception Handling
  68. 68. Exception Handling Exception Types
  69. 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. 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. 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. 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. 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. 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. 75. I/O operations in Java Byte Streams
  76. 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. 77. I/O operations in Java Character Streams
  78. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 102. Network Programming  Terminologies:  IP Address  Protocol  Port Number  MAC Address  Connection-oriented or connection less protocol  Socket Introduction
  103. 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. 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. 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. 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. 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. 108. Thank You Connect on LinkedIn: https://www.linkedin.com/in/aashish-jain-55848216/

Notas del editor

  • Hello this is my note
  • 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.
  • https://j4school.wordpress.com/java-tutorials/core-java/introduction-to-java/java-magic-bytecode-java-virtual-machine-jit-jre-jdk/
  • 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
  • Hello this is my note

×