SlideShare a Scribd company logo
Samsung University Program
What is Java High Level Language Object Oriented programming language Platform Independent Language (Portable) Robust, Secure Multithreaded Built in Networking
Object Oriented Language model organized around "objects" and “data”  Objects have two sections, fields (instance variables) and methods Fields tell you what an object is. Methods tell you what an object does. These fields and methods are closely tied to the object's real world characteristics and behaviour When a program is run objects communicate with each other using methods and variables
Programming Paradigm Programming, at a high level, is the process of solving a problem in an abstract fashion, then writing that solution out in code. Object Orientated Programming and Procedure Oriented Programming are two different ways of thinking about and modeling the problem's solution.
Comparing OOP and PPL Object Oriented programming deals with the elemental basic parts or building blocks of the problem Procedural programming focuses on the steps (procedures and functions) required to produce the desired outcome. In OOL, more emphasis is given on data rather than procedures Programs are divided into Objects and the data is encapsulated (Hidden) from the external environment, providing more security to data. Not applicable to PPL.
Comparing OOP and PPL contd.. In OOL, the Objects communicate with each other via Functions. There is no communication in PPL rather its simply a passing values to the Arguments to the Functions and / or procedures.  OOL concepts includes Inheritance, Encapsulation and Data Abstraction, Polymorphism etc while PPL is simply a traditional way of calling functions and returning values.
Concepts of OOPs Encapsulation - mechanism that binds together code and data in manipulates, and keeps both safe from outside interference and misuse. Inheritance - process by which one object acquires the properties of another object Polymorphism - one name many forms. "one interface, multiple methods". Abstraction - technique of choosing common features of objects and methods is known as abstracting. It also involves with concealing the details and highlighting only the essential features of a particular object or a concept.
Advantages of OOPs Simpler, easier to read programs More efficient reuse of code Faster time to market More robust, error-free code
“ Write Once Run Anywhere” Programs are first written in plain text files ending with the .java extension.  programs are compiled into the Java Virtual Machine (JVM) code called bytecode. File with .class extension Bytecode is machine-independent and can run on any machine  that has JVM The byte code is easily interpreted and therefore can be executed on any platform having a JVM
Robust , Secure No memory pointers Garbage collection -- no bad addresses Bounds checking Programs runs inside the virtual machine sandbox. Exception Handling
Multithreading program’s capability to perform several tasks simultaneously e.g. downloading a video file while playing the video would be considered multithreading Multithreading is particularly useful in graphical user interface (GUI) and network programming.
Java Components Java Virtual Machine.  Java Application Programming Interface (API)
Java Development Kit The Java Development Kit (JDK) is a Sun Microsystems product aimed at Java developers. Program development environment for writing  Java applications It consists of a runtime environment that "sits on top" of the operating system layer as well as the tools and programming that developers need to compile, debug, and run applications written in the Java language.
Installing Java Development Kit SMI -> Knowledge Base ->  Installing JDK Article JDK Stored on path: c:\>Softwares
HANDS On   HANDS On
CLASSPATH The CLASSPATH environment variable is used by Java to determine where to look for classes referenced by a program.  In the CLASSPATH, you do not need to specify the location of normal java packages and classes such as java.util or java.io.IOException. Open the System Properties window (by right-clicking on My Computer and selecting Properties, or through the Control Panel - Start -> Control Panel -> System)
CLASSPATH contd.. On the Advanced tab, click the Environment Variables button. On the Environment Variables windows, if a CLASSPATH variable is already defined, then select it and click Edit. If one is not defined, then click the New button. On the User Variable window, the variable name should be CLASSPATH. Set the value as appropriate. Note that different class file location values should be separated with a semicolon on a Windows machine.
Object Data structures consisting of States (data fields) and behavior (methods) together with their interaction E.g. Dogs : State (name, color, breed ..) & Behavior (barking, fetching ..) object stores its state in fields (variables) and exposes its behavior through methods (functions) Methods operate on an object's state and serve as the primary mechanism for object-to-object communication
Object contd.. class Bicycle { /*Fields, Variables */ int cadence = 0;  /*integer DATA TYPE*/ int speed = 0; int gear = 1; /*Methods*/ void changeCadence(int newValue) {  cadence = newValue;  } void changeGear(int newValue) {  gear = newValue;  } void speedUp(int increment) {  speed = speed + increment;  } void applyBrakes(int decrement) {  speed = speed - decrement;  } }
Class blueprint from which individual objects are created.  this blueprint describes the state and behavior that the objects of the class all share.  An object of a given class is called an instance of the class. Create Bicycle objects Bicycle bike1 = new Bicycle(); Bicycle bike2 = new Bicycle(); Invoke methods on those objects bike1.changeCadence(50); bike2.changeCadence(20);
Elements of Java Literals  - Any number, text, or other information that represents a value.  Example  int abc = 10; private static final int xyz = 25; Identifiers  - Identifiers are the names of variables, methods, classes, packages and interfaces Datatype  - Set of data with values having predefined characteristics and operators you can perform on them Keywords  - Keywords are identifiers that cannot be use by end user as variable name Symbols  - ; , / etc
DataTypes of Java
Java Keywords abstract, assert, boolean, break, byte, case, catch, char, class, const, continue, default, do, double, else, enum, extends, false, final, finally, float, for, goto, if, implements, import, instanceof, int, interface, long, native, new, null, package, private, protected, public, return, short, static, strictfp, super, switch, synchronized, this, throw, throws, transient, true, try, void, volatile, while
Java Symbols ;  Semi-colon indicates the end of a statement () Parentheses used in several places including: method, casting [] square brackets used in array declaration {} curly braces used to enclose the code of method // Indicates a single line comment /*..*/  comments that can span more than one line.
Java Symbols contd.. :  colon used in switch statements and in conditional operator. " " Double quotes surround a string literal. ' ' Single quotes surround a character literal. +,-,etc Operator symbols.  ?  Used with the conditional operator  x = boolean ? y : z;
HelloProfessor Program Open any TextEditor and write down the following program /* The HelloProfessor class implements an application that displays result to the standard output. */ public class HelloProfessor { /*visibility [final] [static][synchronize] dataType variable name [ = initialization value ]*/ public final static String ProfessorName = "Type your name here"; public String SMI = "SMI"; public HelloProfessor()  {  }  /*Constructor*/ /*visibility [final] [static][synchronize] returnType methodName([parameterList])*/ public static void main(String args[])  {   /*HelloProfessor Object*/   HelloProfessor helloProfessor = new HelloProfessor();   /*display result on Standard Output*/   System.out.println("Hello "+HelloProfessor.ProfessorName);    System.out.println("Welcome to Samsung University Program!!!");   System.out.println("Welcome to "+helloProfessor.SMI);   } } Save file as HelloProfessor.java
HelloProfessor Program Contd.. name of class is same as name of file ( .java extension) body of class surrounded by  {  } this class has one method called main. All Java applications must have a main method in one of the classes. execution starts here body of method within {  } all other statements end with semicolon ;
Compiling HelloProfessor Program Use compiler called javac which is provided by java. Go to the command prompt and type drive:\ > javac HelloProfessor.java javac compiler will create a class file called HelloProfessor.class that contains only bytecodes. These bytecodes have to be interpreted by a Java Virtual Machine(JVM) that will convert the bytecodes into machine codes.
Running HelloProfessor Program Once we successfully compiled the program, we need to run the program in order to get the output.  this can be done by the java interpreter called java. In the command line type as shown here. Go to the command prompt and type  drive:\ > java HelloProfessor the output will be displayed as Hello  Professor name
Methods  information needed to do their job methods break down large problems into smaller ones your program may call the same method many times saves writing and maintaining same code methods can take parameters  methods can return a value. must specify type of value returned
Method Signature   visibility [static] returnType methodName(parameterList) visibility: public  : accessible to other objects and classes protected : accessible to classes which inherit from this one private : accessible only to own class default : access only to classes within same package static keyword: use when method belongs to class as whole not object of the class
Method Signature contd.. return type: specifies type of information returned. can be a simple data type int, float, double, char, String, boolean or a class if nothing returned, use keyword void method name parameterList:   list of datatype , objects etc comma seperated list
Variable Signature visibility [final] [static] datatype variableName visibility: public  : accessible to other objects and classes protected : accessible to classes which inherit from this one private :  accessible to own class default : access to classes within same package. static keyword: when method belongs to class as whole and not object  final keyword: constant value that cannot be changed
Application Structure [package  packagename ;] [import  packagename.classname ;] or [import  packagename.*; ] [visibility] [abstract] [static] [final] class  classname  [implements  interfacename ] [extends  superclass ]  OR [visibility] interface  interfacename  [extends  interfacename ] {   [ [visibility] [static] [final] [datatype  varaible  =  initialization ;] ]   [constructor] /*method without return type & method name same as classname*/ [ [visibility] [static] [final] [returnType] [ methodname ] ( [  parameterList  ] ) { } ] }
Application Structure contd.. public - indicates that the method can be called by any object static - indicates that the method is a class method, which can be called without the requirement to instantiate an object of the class void - indicates that the method doesn't return any value main(String args[]) - it's the entry point for your application and will subsequently invoke all the other methods required by your program.
Constructor creates an Object of the class i.e. it initialize all instance variables and creates place in memory to hold the Object. Constructor name is the same as the class name  Instead of a return type and a name, just use the class name  Every class has a constructor to make its objects If you don’t define a constructor, a default one will be created. Sets all the fields of the new object to default value  (if not provided) You can supply arguments
Visibilty of variable / methods public: keyword applied to a class, makes it available/visible everywhere. Applied to a method or variable, completely visible. private: fields or methods for a class only visible within that class. Private members are not visible within subclasses, and are not inherited. protected: members of a class are visible within the class, subclasses and also within all classes that are in the same package as that class.
Package Java’s way of grouping a number of related classes and/or interfaces together into a single unit. Programmers also typically use packages to organize classes belonging to the same category or providing similar functionality. The package statement must appear as the first statement in a file of Java source code, if it appears  e.g. package abc;  A package is the Java version of a library
Benefits of Package The classes contained in the packages of other programs/applications can be reused. Resolves classname conflicts: two classes in two different packages can have the same name. If there is a naming clash, then classes can be accessed with their fully qualified name. Classes in packages can be hidden if we don’t want other packages to access them. Classes in the same package can access each other's package-access members.
Visibility of Package
Import There are two ways of accessing the classes or class methods stored in packages: Using fully qualified class name java.lang.Math.sqrt(x); Import package and use class name directly. The import directive tells the compiler where to look for the class definitions when it comes upon a class. import java.lang.Math and then use Math.sqrt(x);
Import contd.. Selected or all classes in packages can be imported: import package.class; or import package.*; By default Implicit in all programs: import java.lang.*; The general form of importing package is: import package1[.package2][…].[classname][.*]; Example: import myPackage.ClassA;  or    import myPackage.secondPackage.*;
Operators & Control Flows Almost exactly like regular ANSI C. +, *, -, /, %, ++, --, +=, etc. ==, !=, >, < , etc. if statements, for loops, while loops, do loops, switch statements, etc. continue, break, return.
Final classes , methods, variables Final class, why? - increase system security: disables creating a subclass of a class and then substituting for the original one  - good object-oriented design: your class should have no subclasses  Final methods, why? - To protect some of your class's methods from being overridden declare them final. Final variables, why? - Doesn’t allow to change the value of the variable.
Constructor Invocation The constructors are called either explicitly or implicitly from base-class to sub-class down the inheritance hierarchy. The compiler forces invocation of base-class constructor as the first thing that happens in the sub-class constructor , this means you cannot catch any exception thrown in the base-class's constructor.
Inheritance All Java classes are arranged in a hierarchy, starting with Object, which is the superclass of all Java classes Inheritance in OOP is analogous to inheritance in humans Inheritance and hierarchical organization allow you to capture the idea that one thing may be a refinement or extension of another Inheritance allows a software developer to derive a new class from an existing one, for the purpose of reuse, enhancement, adaptation, etc.
Inheritance contd.. The existing class is called the parent class, or superclass, or base class  The derived class is called the child class or subclass. As the name implies, the child inherits characteristics of the parent That is, the child class inherits the methods and data defined for the parent class. creates a IS-A relationship meaning child is a more specific version of parent.
Class Hierarchy A child class of one parent can be the parent of another child, forming  class hierarchies   At the top of the hierarchy there’s a default class called  Object .
Extends In Java, we use the reserved word extends to establish an inheritance relationship.  Multiple inheritance is not supported in java public class Parent {   /* class contents */   int weight;    public int getWeight() {…}  } public class Child extends Parent {   /* class contents */   public void write() {…}   public int getWeight() {…}  /* override */   public int getWeight(int abc) {…}  /* overload */ }
Overriding If a method in a subclass has the same name and type signature as a method in its superclass, then method in the subclass is said to override the method in superclass. The overriding method has the same name, number and type of parameters, and return type as the method it overrides. In java, all methods except of constructors can override the methods of their ancestor class. If a method is declared with final modifier, it cannot be overridden
Overriding contd.. A subclass must override methods that are declared abstract in the superclass, or the subclass itself must be abstract. If a subclass defines a class method with the same signature as a class method in the superclass, the method in the subclass hides the one in the superclass. The access specifier for an overriding method can allow more, but not less, access than the overridden method. For example, a protected instance method in the superclass can be made public, but not private, in the subclass.
Overriding vs Shadowing The distinction between shadowing and overriding has important implications.  public class Animal {    public static void hide() { System.out.println(&quot;The hide method in Animal.”); }   public void override() { System.out.println(&quot;The override method in Animal.&quot;); }  } public class Cat extends Animal {   public static void hide() { System.out.println(&quot;The hide method in Cat.&quot;); }    public void override() { System.out.println(&quot;The override method in Cat.&quot;); }      public static void main(String[] args) {    Animal  animal = new Cat();    animal.hide();   animal.override();   } }   Output:  The hide method in Animal. The override method in Cat.
Overriding access modifiers The access specifier for an overriding method can allow more, but not less, access than the overridden method. For example, a protected instance method in the superclass can be made public, but not private, in the subclass. You will get a compile-time error if you attempt to change an instance method in the superclass to a class method in the subclass, and vice versa.
Overloading In Java it is possible to define two or more methods within the same class that share the same name, as long as their parameter declarations are different. When this is the case, the methods are said to be overloaded, and the process is referred to as method overloading.  Method overloading is one of the ways that Java implements polymorphism.
Overloading contd.. class Overloading {   void test() { System.out.println(&quot;No parameters&quot;); }   void test(int a, int b) { System.out.println(&quot;a and b: &quot; + a + &quot; &quot; + b); }   void test(float a) { System.out.println(&quot;Inside test(double) a: &quot; + a); } } class Overload {   public static void main(String args[]) {   Overloading ob = new Overloading();   ob.test();   ob.test(10, 20);   ob.test(123.2);   } }
“ this” “ this” is a reference to the current object — the object whose method or constructor is being called. You can refer to any member of the current object from within an instance method or a constructor by using this. Can be used with variables or methods or constructors.
Using “this” with a Field The most common reason for using the this keyword is because a field is shadowed by a method or constructor parameter.    public class Point {   public int x = 0;   public int y = 0;  /* constructor */ public Point(int x, int y) {   this.x = x;     this.y = y; } } Each argument to the constructor shadows one of the object's fields - inside the constructor x is a local copy of the constructor's first argument. To refer to the Point field x, the constructor must use this.x.
Using “this” with a Constructor From within a constructor, you can also use ‘this’ to call another constructor in the same class. Also called as explicit constructor invocation.    public class Rectangle { private int x, y, width, height; public Rectangle(int width, int height) {   this(0, 0, width, height); }   public Rectangle(int x, int y, int width, int height) {   this.x = x;  this.y = y; this.width = width;  this.height = height; } } Compiler determines which constructor to call, based on the number and type of arguments.
“ super” refers to the superclass (base class) usage: with a variable or method (most common with a method) as a function inside a constructor of the subclass you can invoke the overridden method through the use of the keyword super can also use super to refer to a hidden field (not recommended)
Accessing Superclass Members If your method overrides one of its superclass's methods, you can invoke the overridden method through the use of the keyword super.  public class Superclass {   public void printMethod() {   System.out.println(&quot;Printed in Superclass.&quot;);   } } Here is a subclass, called Subclass, that overrides printMethod(): public class Subclass extends Superclass { public void printMethod() {  /*overrides printMethod in Superclass*/   super.printMethod();   System.out.println(&quot;Printed in Subclass&quot;); } }
Accessing Superclass Constructor With super(), the super class no-argument constructor is called. With super(parameter list), the superclass constructor with a matching parameter list is called. class Employee {   public Employee(String name, double salary) {  ……  } } class Manager extends Employee {  private double bonus; public void setBonus(double bb) { …}  public Manager ( String name, double salary, double bonus ) {    super(name, salary);   this.bonus = bonus;  }  }
Abstract There are situations in which you will want to define a superclass that declares the structure of a given abstraction without providing a complete implementation of every method.  Sometimes you will want to create a superclass that only defines a generalized form that will be shared by all of its subclasses, leaving it to each subclass to fill in the details. One way this situation can occur is when a superclass is unable to create a meaningful implementation for a method.  Example consider Superclass figure in which area() cannot be implemented. The definition of area() is simply a placeholder. It will not compute and display the area of any type of object.
Abstract contd.. you want some way to ensure that a subclass does, indeed, override all necessary methods. Java's solution to this problem is the abstract method. An abstract class is a class that is declared abstract - it may or may not include abstract methods Abstract classes cannot be instantiated, but can be subclassed.  An abstract method is a method that is declared without an implementation (without braces, and followed by a semicolon),  abstract type name(parameter-list); Any class that contains one or more abstract methods must also be declared abstract.
Abstract contd.. When an abstract class is subclassed, the subclass usually provides implementations for all of the abstract methods in its parent class. However, if it does not, the subclass must also be declared abstract. Abstract classes can include as much implementation as they see fit. Although abstract classes cannot be used to instantiate objects, they can be used to create object references, because Java's approach to run-time polymorphism is implemented through the use of superclass references.
Abstract contd.. /* Using abstract methods and classes.*/   abstract class Figure {   double dim1, dim2;   Figure(double a, double b) {  dim1 = a;  dim2 = b;  } /* area is now an abstract method */   abstract double area();   }   class Rectangle extends Figure {   Rectangle(double a, double b) {   super(a, b);   }   /* override area for rectangle*/   double area() {   System.out.println(&quot;Inside Area for Rectangle.&quot;);   return dim1 * dim2;   } }
Abstract contd.. class Triangle extends Figure {   Triangle(double a, double b)  {  super(a, b);  }   /* override area for right triangle*/   double area() {   System.out.println(&quot;Inside Area for Triangle.&quot;);   return dim1 * dim2 / 2;   } } class AbstractAreas {   public static void main(String args[]) {   // Figure f = new Figure(10, 10);  /* illegal cannot be instantiated*/   Rectangle r = new Rectangle(9, 5);   Triangle t = new Triangle(10, 8);   Figure figref;  /* this is OK, no object is created */   figref = r;   System.out.println(&quot;Area is &quot; + figref.area());   figref = t;   System.out.println(&quot;Area is &quot; + figref.area());   } }
Interface In Java an interface is similar to an abstract class in that its members are not implemented. Interfaces are declared using the interface keyword, and may only contain method signatures and constant declarations (variable declarations that are declared to be both static and final).  An interface may never contain method definitions. An interface may extend, any number of interfaces. As interfaces are implicitly abstract, they cannot be directly instantiated except when instantiated by a class that implements the said interface.
Interface contd.. If your class claims to implement an interface, all methods defined by that interface must appear in its source code before the class to successfully compile.  Interface can only be implemented by classes or extended by other interfaces. An interface may not implement an interface benefit of using interfaces is that they simulate multiple inheritance.
Interface contd.. Defining an interface is similar to creating a new class:  public interface OperateCar {    /*constant declarations, if any*/   int signalTurn(Direction direction, boolean signalOn);   int getRadarFront(double distanceToCar, double speedOfCar);   int getRadarRear(double distanceToCar, double speedOfCar);   ......   /*more method signatures*/ } Note that the method signatures have no braces and are terminated with a semicolon.
Polymorphism Polymorphism is a term that describes a situation where one name may refer to different methods. In java there are two type of polymorphism: overloading type and overriding type. When you override methods, java determines the proper methods to call at the program’s run time. Overriding occurs when a class method has the same name and signature as a method in parent class. Overloading occurs when several methods have same names with different method signature. Overloading is determined at the compile time.
Encapsulation hiding information from unwanted outside access and attaching that information to only methods that need access to it. binds data and operations tightly together and separates them from external access that may corrupt them intentionally or unintentionally.  Encapsulation is achieved by declaring variables, methods, class with access modifiers Providing access through the use of public accessor (getter) and mutator (setter) methods.
Data Abstraction Data abstraction and encapsulation are closely tied together. simple definition of data abstraction is the development of classes, objects, types in terms of their interfaces and functionality, instead of their implementation details. Abstraction is used to manage complexity. Abstraction  decompose complex systems into smaller components  Implementation (Encapsulation) is the next step
Threads Software that can do multiple things simultaneously is known as concurrent software. In concurrent programming, there are two basic units of execution: processes and threads. In the Java programming language, concurrent programming is mostly concerned with threads. However, processes are also important.  A computer system normally has many active processes and threads. A thread is an independent path of execution within a program. Threads are sometimes called lightweight processes.
Threads contd.. Threads exist within a process — every process has at least one. Threads share the process's resources, including memory and open files. Threads communicate via shared access to data JVM allows an application to have multiple threads of execution running concurrently.  Multiple threads in process execute same program A Java program can have many threads, and these threads can run concurrently, either asynchronously or synchronously Every thread in Java is created and controlled by the java.lang.Thread class
Threads contd.. Multithreading refers to two or more tasks executing concurrently within a single program. Advantages: - Threads are lightweight compared to processes - Threads share the same address space and therefore can share    both data and code - Context switching between threads is usually less expensive  than between processes - Cost of thread intercommunication is relatively low that that of  process intercommunication - Threads allow different tasks to be performed concurrently.
Creating Threads Two ways of creating threads:  -  implementing an Runnable interface -  extending a Thread class.
Runnable Interface Implementing Runnable Interface The Runnable Interface Signature public interface Runnable { void run(); } implement the Runnable Interface and then instantiate an object of the class.  override the run() method into your class which is the only method that needs to be implemented. The run() method contains the logic of the thread.
Runnable Interface contd.. class RunnableThread implements Runnable {  Thread runner; public RunnableThread() { }   public RunnableThread(String threadName) {    runner = new Thread(this);  /*(1) Create a new thread. */   runner.start();  /*(2) Start the thread. */ }   public void run() {    /*Display info about this particular thread*/   System.out.println(Thread.currentThread());  } }
Thread Class Extending Thread class class XThread extends Thread { XThread() { }  XThread(String threadName) {  super(threadName);  /*Initialize thread. */ System.out.println(this); start();  } public void run() {  /*Display info about this particular thread */ System.out.println(Thread.currentThread().getName());  } }
Exceptions An exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions.  An exception is an object that enables a program to handle unusual/erroneous situations A method can throw  an exception void doubleArray( int[] A) throws Exception { … if (Index >= A.length)    throw new Exception( “array too small ” + Index) … }
Exceptions contd.. Exception is a class, and all Exception-like objects should be subclasses of Exception.
Extending Exception A method can throw several exceptions (each of which is a subclass of the Exception class) public void scaleArray( int[] A, int s) throws  ArrayRangeException, IllegalArgumentException  {  …   if (Index >= A.length)   throw new ArrayRangeException( “array too small ” + Index)  … } class ArrayRangeException must be a subclass of (predefined) class Exception, and one of its constructors takes a string argument class IllegalArgumentException is predefined
Exception Propagation A (caller) method can deal with an exception thrown by the method it calls in 2 ways: caller method can ignore exception handling In this case the exception thrown by the called method will be “passed up” and (effectively) thrown by the caller method This exception propagation will continue until the main method which was an access point of the java code, which will throw an error to the user (and print its description in the console output)
Exception Propagation contd.. Except if any of the methods along the caller/callee chain explicitly handles this exception.  This breaks the chain of exception propagation, and after the exception is handled, the control returns to normal execution.
Try Catch Statement The try/catch statement encloses some code and is used to handle errors and exceptions that might occur in that code. try {   body-code  /*code that might throw exception */ } catch (exception-classname variable-name) {   handler-code  } The variable-name specifies a name for a variable that will hold the exception object if the exception occurs. Finally, the handler-code contains the code to execute if the exception occurs
Try Catch Statement contd.. It is possible to specify more than one exception handler in a try/catch statement. When an exception occurs, each handler is checked in order (i.e. top-down) and the handler that first matches is executed. try { ……… } catch(<exceptionclass_1> <obj1>) { /*statements to handle the exception*/   } catch(<exceptionclass_2> <obj2>) { /*statements to handle the exception*/   }
Try Catch Statement contd.. When an exception is thrown, normal execution is suspended. The runtime system proceeds to find a matching catch block that can handle the exception. If no handler is found, then the exception is dealt with by the default exception handler at the top level. try { int num1 = 10; int num2 = 0; int[] intarr = {0,1,2,3,4}; res = num1 / num2;   }catch (ArrayIndexOutOfBoundsException e) {   System.out.println(&quot;Error…. Array is out of Bounds&quot;);   }catch (ArithmeticException e) {    System.out.println (&quot;Can't be divided by Zero&quot;);    }
Finally Statement The finally block always executes when the try block exits. This ensures that the finally block is executed even if an unexpected exception occurs. allows the programmer to avoid having cleanup code accidentally bypassed by a return, continue, or break.  Putting cleanup code in a finally block is always a good practice, even when no exceptions are anticipated.
Finally Statement contd.. try{ … }catch(Exception obj) { … }finally { … } The runtime system always executes the statements within the finally block regardless of what happens within the try block. So it's the perfect place to perform cleanup
Thankyou THANKYOU

More Related Content

What's hot (20)

Basics of Java
Basics of JavaBasics of Java
Basics of Java
Sherihan Anver
 
Basic Java Programming
Basic Java ProgrammingBasic Java Programming
Basic Java Programming
Math-Circle
 
Java tutorial PPT
Java tutorial PPTJava tutorial PPT
Java tutorial PPT
Intelligo Technologies
 
Core Java introduction | Basics | free course
Core Java introduction | Basics | free course Core Java introduction | Basics | free course
Core Java introduction | Basics | free course
Kernel Training
 
Core Java
Core JavaCore Java
Core Java
Prakash Dimmita
 
Java &amp; advanced java
Java &amp; advanced javaJava &amp; advanced java
Java &amp; advanced java
BASAVARAJ HUNSHAL
 
Java platform
Java platformJava platform
Java platform
BG Java EE Course
 
java: basics, user input, data type, constructor
java:  basics, user input, data type, constructorjava:  basics, user input, data type, constructor
java: basics, user input, data type, constructor
Shivam Singhal
 
Java Programming
Java ProgrammingJava Programming
Java Programming
Anjan Mahanta
 
Unit of competency
Unit of competencyUnit of competency
Unit of competency
loidasacueza
 
Introduction to Java programming - Java tutorial for beginners to teach Java ...
Introduction to Java programming - Java tutorial for beginners to teach Java ...Introduction to Java programming - Java tutorial for beginners to teach Java ...
Introduction to Java programming - Java tutorial for beginners to teach Java ...
Duckademy IT courses
 
Lecture 3 java basics
Lecture 3 java basicsLecture 3 java basics
Lecture 3 java basics
the_wumberlog
 
Core Java Tutorial
Core Java TutorialCore Java Tutorial
Core Java Tutorial
eMexo Technologies
 
Core java
Core javaCore java
Core java
Shivaraj R
 
Elements of Java Language
Elements of Java Language Elements of Java Language
Elements of Java Language
Hitesh-Java
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to java
Ajay Sharma
 
Core Java
Core JavaCore Java
Core Java
christ university
 
Notes of java first unit
Notes of java first unitNotes of java first unit
Notes of java first unit
gowher172236
 
Java training in delhi
Java training in delhiJava training in delhi
Java training in delhi
APSMIND TECHNOLOGY PVT LTD.
 
Core java
Core java Core java
Core java
Ravi varma
 

Viewers also liked (7)

Jsr75 sup
Jsr75 supJsr75 sup
Jsr75 sup
SMIJava
 
Jsr120 sup
Jsr120 supJsr120 sup
Jsr120 sup
SMIJava
 
JSR 82 (bluetooth obex)
JSR 82 (bluetooth obex)JSR 82 (bluetooth obex)
JSR 82 (bluetooth obex)
SMIJava
 
Jsr135 sup
Jsr135 supJsr135 sup
Jsr135 sup
SMIJava
 
SMI - Introduction to JSR 75 PIM
SMI - Introduction to JSR 75 PIMSMI - Introduction to JSR 75 PIM
SMI - Introduction to JSR 75 PIM
SMIJava
 
Java ME CLDC MIDP
Java ME CLDC MIDPJava ME CLDC MIDP
Java ME CLDC MIDP
SMIJava
 
Push registrysup
Push registrysupPush registrysup
Push registrysup
SMIJava
 
Jsr75 sup
Jsr75 supJsr75 sup
Jsr75 sup
SMIJava
 
Jsr120 sup
Jsr120 supJsr120 sup
Jsr120 sup
SMIJava
 
JSR 82 (bluetooth obex)
JSR 82 (bluetooth obex)JSR 82 (bluetooth obex)
JSR 82 (bluetooth obex)
SMIJava
 
Jsr135 sup
Jsr135 supJsr135 sup
Jsr135 sup
SMIJava
 
SMI - Introduction to JSR 75 PIM
SMI - Introduction to JSR 75 PIMSMI - Introduction to JSR 75 PIM
SMI - Introduction to JSR 75 PIM
SMIJava
 
Java ME CLDC MIDP
Java ME CLDC MIDPJava ME CLDC MIDP
Java ME CLDC MIDP
SMIJava
 
Push registrysup
Push registrysupPush registrysup
Push registrysup
SMIJava
 
Ad

Similar to SMI - Introduction to Java (20)

Java for Mainframers
Java for MainframersJava for Mainframers
Java for Mainframers
Rich Helton
 
Unit 1 – Introduction to Java- (Shilpa R).pptx
Unit 1 – Introduction to Java- (Shilpa R).pptxUnit 1 – Introduction to Java- (Shilpa R).pptx
Unit 1 – Introduction to Java- (Shilpa R).pptx
shilpar780389
 
Introduction
IntroductionIntroduction
Introduction
richsoden
 
Java interview questions and answers
Java interview questions and answersJava interview questions and answers
Java interview questions and answers
Krishnaov
 
Java notes
Java notesJava notes
Java notes
Upasana Talukdar
 
ANDROID FDP PPT
ANDROID FDP PPTANDROID FDP PPT
ANDROID FDP PPT
skumartarget
 
Java notes
Java notesJava notes
Java notes
Debasish Biswas
 
Java
JavaJava
Java
Sneha Mudraje
 
Java1
Java1Java1
Java1
computertuitions
 
Java
Java Java
Java
computertuitions
 
brief introduction to core java programming.pptx
brief introduction to core java programming.pptxbrief introduction to core java programming.pptx
brief introduction to core java programming.pptx
ansariparveen06
 
Java_presesntation.ppt
Java_presesntation.pptJava_presesntation.ppt
Java_presesntation.ppt
VGaneshKarthikeyan
 
imperative programming language, java, android
imperative programming language, java, androidimperative programming language, java, android
imperative programming language, java, android
i i
 
Javalecture 1
Javalecture 1Javalecture 1
Javalecture 1
mrinalbhutani
 
01slide
01slide01slide
01slide
Usha Sri
 
01slide
01slide01slide
01slide
cdclabs_123
 
Javanotes
JavanotesJavanotes
Javanotes
John Cutajar
 
1.introduction to java
1.introduction to java1.introduction to java
1.introduction to java
Madhura Bhalerao
 
Introduction java programming
Introduction java programmingIntroduction java programming
Introduction java programming
Nanthini Kempaiyan
 
Classes and Objects
Classes and ObjectsClasses and Objects
Classes and Objects
vmadan89
 
Java for Mainframers
Java for MainframersJava for Mainframers
Java for Mainframers
Rich Helton
 
Unit 1 – Introduction to Java- (Shilpa R).pptx
Unit 1 – Introduction to Java- (Shilpa R).pptxUnit 1 – Introduction to Java- (Shilpa R).pptx
Unit 1 – Introduction to Java- (Shilpa R).pptx
shilpar780389
 
Introduction
IntroductionIntroduction
Introduction
richsoden
 
Java interview questions and answers
Java interview questions and answersJava interview questions and answers
Java interview questions and answers
Krishnaov
 
brief introduction to core java programming.pptx
brief introduction to core java programming.pptxbrief introduction to core java programming.pptx
brief introduction to core java programming.pptx
ansariparveen06
 
imperative programming language, java, android
imperative programming language, java, androidimperative programming language, java, android
imperative programming language, java, android
i i
 
Classes and Objects
Classes and ObjectsClasses and Objects
Classes and Objects
vmadan89
 
Ad

Recently uploaded (20)

Enabling BIM / GIS integrations with Other Systems with FME
Enabling BIM / GIS integrations with Other Systems with FMEEnabling BIM / GIS integrations with Other Systems with FME
Enabling BIM / GIS integrations with Other Systems with FME
Safe Software
 
Floods in Valencia: Two FME-Powered Stories of Data Resilience
Floods in Valencia: Two FME-Powered Stories of Data ResilienceFloods in Valencia: Two FME-Powered Stories of Data Resilience
Floods in Valencia: Two FME-Powered Stories of Data Resilience
Safe Software
 
Crypto Super 500 - 14th Report - June2025.pdf
Crypto Super 500 - 14th Report - June2025.pdfCrypto Super 500 - 14th Report - June2025.pdf
Crypto Super 500 - 14th Report - June2025.pdf
Stephen Perrenod
 
The State of Web3 Industry- Industry Report
The State of Web3 Industry- Industry ReportThe State of Web3 Industry- Industry Report
The State of Web3 Industry- Industry Report
Liveplex
 
How to Detect Outliers in IBM SPSS Statistics.pptx
How to Detect Outliers in IBM SPSS Statistics.pptxHow to Detect Outliers in IBM SPSS Statistics.pptx
How to Detect Outliers in IBM SPSS Statistics.pptx
Version 1 Analytics
 
Your startup on AWS - How to architect and maintain a Lean and Mean account J...
Your startup on AWS - How to architect and maintain a Lean and Mean account J...Your startup on AWS - How to architect and maintain a Lean and Mean account J...
Your startup on AWS - How to architect and maintain a Lean and Mean account J...
angelo60207
 
Domino IQ – What to Expect, First Steps and Use Cases
Domino IQ – What to Expect, First Steps and Use CasesDomino IQ – What to Expect, First Steps and Use Cases
Domino IQ – What to Expect, First Steps and Use Cases
panagenda
 
Precisely Demo Showcase: Powering ServiceNow Discovery with Precisely Ironstr...
Precisely Demo Showcase: Powering ServiceNow Discovery with Precisely Ironstr...Precisely Demo Showcase: Powering ServiceNow Discovery with Precisely Ironstr...
Precisely Demo Showcase: Powering ServiceNow Discovery with Precisely Ironstr...
Precisely
 
Bridging the divide: A conversation on tariffs today in the book industry - T...
Bridging the divide: A conversation on tariffs today in the book industry - T...Bridging the divide: A conversation on tariffs today in the book industry - T...
Bridging the divide: A conversation on tariffs today in the book industry - T...
BookNet Canada
 
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Safe Software
 
If You Use Databricks, You Definitely Need FME
If You Use Databricks, You Definitely Need FMEIf You Use Databricks, You Definitely Need FME
If You Use Databricks, You Definitely Need FME
Safe Software
 
PyData - Graph Theory for Multi-Agent Integration
PyData - Graph Theory for Multi-Agent IntegrationPyData - Graph Theory for Multi-Agent Integration
PyData - Graph Theory for Multi-Agent Integration
barqawicloud
 
Down the Rabbit Hole – Solving 5 Training Roadblocks
Down the Rabbit Hole – Solving 5 Training RoadblocksDown the Rabbit Hole – Solving 5 Training Roadblocks
Down the Rabbit Hole – Solving 5 Training Roadblocks
Rustici Software
 
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOMEstablish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Anchore
 
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdfHow Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
Rejig Digital
 
Introduction to Typescript - GDG On Campus EUE
Introduction to Typescript - GDG On Campus EUEIntroduction to Typescript - GDG On Campus EUE
Introduction to Typescript - GDG On Campus EUE
Google Developer Group On Campus European Universities in Egypt
 
Developing Schemas with FME and Excel - Peak of Data & AI 2025
Developing Schemas with FME and Excel - Peak of Data & AI 2025Developing Schemas with FME and Excel - Peak of Data & AI 2025
Developing Schemas with FME and Excel - Peak of Data & AI 2025
Safe Software
 
Agentic AI: Beyond the Buzz- LangGraph Studio V2
Agentic AI: Beyond the Buzz- LangGraph Studio V2Agentic AI: Beyond the Buzz- LangGraph Studio V2
Agentic AI: Beyond the Buzz- LangGraph Studio V2
Shashikant Jagtap
 
Domino IQ – Was Sie erwartet, erste Schritte und Anwendungsfälle
Domino IQ – Was Sie erwartet, erste Schritte und AnwendungsfälleDomino IQ – Was Sie erwartet, erste Schritte und Anwendungsfälle
Domino IQ – Was Sie erwartet, erste Schritte und Anwendungsfälle
panagenda
 
“Solving Tomorrow’s AI Problems Today with Cadence’s Newest Processor,” a Pre...
“Solving Tomorrow’s AI Problems Today with Cadence’s Newest Processor,” a Pre...“Solving Tomorrow’s AI Problems Today with Cadence’s Newest Processor,” a Pre...
“Solving Tomorrow’s AI Problems Today with Cadence’s Newest Processor,” a Pre...
Edge AI and Vision Alliance
 
Enabling BIM / GIS integrations with Other Systems with FME
Enabling BIM / GIS integrations with Other Systems with FMEEnabling BIM / GIS integrations with Other Systems with FME
Enabling BIM / GIS integrations with Other Systems with FME
Safe Software
 
Floods in Valencia: Two FME-Powered Stories of Data Resilience
Floods in Valencia: Two FME-Powered Stories of Data ResilienceFloods in Valencia: Two FME-Powered Stories of Data Resilience
Floods in Valencia: Two FME-Powered Stories of Data Resilience
Safe Software
 
Crypto Super 500 - 14th Report - June2025.pdf
Crypto Super 500 - 14th Report - June2025.pdfCrypto Super 500 - 14th Report - June2025.pdf
Crypto Super 500 - 14th Report - June2025.pdf
Stephen Perrenod
 
The State of Web3 Industry- Industry Report
The State of Web3 Industry- Industry ReportThe State of Web3 Industry- Industry Report
The State of Web3 Industry- Industry Report
Liveplex
 
How to Detect Outliers in IBM SPSS Statistics.pptx
How to Detect Outliers in IBM SPSS Statistics.pptxHow to Detect Outliers in IBM SPSS Statistics.pptx
How to Detect Outliers in IBM SPSS Statistics.pptx
Version 1 Analytics
 
Your startup on AWS - How to architect and maintain a Lean and Mean account J...
Your startup on AWS - How to architect and maintain a Lean and Mean account J...Your startup on AWS - How to architect and maintain a Lean and Mean account J...
Your startup on AWS - How to architect and maintain a Lean and Mean account J...
angelo60207
 
Domino IQ – What to Expect, First Steps and Use Cases
Domino IQ – What to Expect, First Steps and Use CasesDomino IQ – What to Expect, First Steps and Use Cases
Domino IQ – What to Expect, First Steps and Use Cases
panagenda
 
Precisely Demo Showcase: Powering ServiceNow Discovery with Precisely Ironstr...
Precisely Demo Showcase: Powering ServiceNow Discovery with Precisely Ironstr...Precisely Demo Showcase: Powering ServiceNow Discovery with Precisely Ironstr...
Precisely Demo Showcase: Powering ServiceNow Discovery with Precisely Ironstr...
Precisely
 
Bridging the divide: A conversation on tariffs today in the book industry - T...
Bridging the divide: A conversation on tariffs today in the book industry - T...Bridging the divide: A conversation on tariffs today in the book industry - T...
Bridging the divide: A conversation on tariffs today in the book industry - T...
BookNet Canada
 
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Safe Software
 
If You Use Databricks, You Definitely Need FME
If You Use Databricks, You Definitely Need FMEIf You Use Databricks, You Definitely Need FME
If You Use Databricks, You Definitely Need FME
Safe Software
 
PyData - Graph Theory for Multi-Agent Integration
PyData - Graph Theory for Multi-Agent IntegrationPyData - Graph Theory for Multi-Agent Integration
PyData - Graph Theory for Multi-Agent Integration
barqawicloud
 
Down the Rabbit Hole – Solving 5 Training Roadblocks
Down the Rabbit Hole – Solving 5 Training RoadblocksDown the Rabbit Hole – Solving 5 Training Roadblocks
Down the Rabbit Hole – Solving 5 Training Roadblocks
Rustici Software
 
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOMEstablish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Anchore
 
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdfHow Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
Rejig Digital
 
Developing Schemas with FME and Excel - Peak of Data & AI 2025
Developing Schemas with FME and Excel - Peak of Data & AI 2025Developing Schemas with FME and Excel - Peak of Data & AI 2025
Developing Schemas with FME and Excel - Peak of Data & AI 2025
Safe Software
 
Agentic AI: Beyond the Buzz- LangGraph Studio V2
Agentic AI: Beyond the Buzz- LangGraph Studio V2Agentic AI: Beyond the Buzz- LangGraph Studio V2
Agentic AI: Beyond the Buzz- LangGraph Studio V2
Shashikant Jagtap
 
Domino IQ – Was Sie erwartet, erste Schritte und Anwendungsfälle
Domino IQ – Was Sie erwartet, erste Schritte und AnwendungsfälleDomino IQ – Was Sie erwartet, erste Schritte und Anwendungsfälle
Domino IQ – Was Sie erwartet, erste Schritte und Anwendungsfälle
panagenda
 
“Solving Tomorrow’s AI Problems Today with Cadence’s Newest Processor,” a Pre...
“Solving Tomorrow’s AI Problems Today with Cadence’s Newest Processor,” a Pre...“Solving Tomorrow’s AI Problems Today with Cadence’s Newest Processor,” a Pre...
“Solving Tomorrow’s AI Problems Today with Cadence’s Newest Processor,” a Pre...
Edge AI and Vision Alliance
 

SMI - Introduction to Java

  • 2. What is Java High Level Language Object Oriented programming language Platform Independent Language (Portable) Robust, Secure Multithreaded Built in Networking
  • 3. Object Oriented Language model organized around &quot;objects&quot; and “data” Objects have two sections, fields (instance variables) and methods Fields tell you what an object is. Methods tell you what an object does. These fields and methods are closely tied to the object's real world characteristics and behaviour When a program is run objects communicate with each other using methods and variables
  • 4. Programming Paradigm Programming, at a high level, is the process of solving a problem in an abstract fashion, then writing that solution out in code. Object Orientated Programming and Procedure Oriented Programming are two different ways of thinking about and modeling the problem's solution.
  • 5. Comparing OOP and PPL Object Oriented programming deals with the elemental basic parts or building blocks of the problem Procedural programming focuses on the steps (procedures and functions) required to produce the desired outcome. In OOL, more emphasis is given on data rather than procedures Programs are divided into Objects and the data is encapsulated (Hidden) from the external environment, providing more security to data. Not applicable to PPL.
  • 6. Comparing OOP and PPL contd.. In OOL, the Objects communicate with each other via Functions. There is no communication in PPL rather its simply a passing values to the Arguments to the Functions and / or procedures. OOL concepts includes Inheritance, Encapsulation and Data Abstraction, Polymorphism etc while PPL is simply a traditional way of calling functions and returning values.
  • 7. Concepts of OOPs Encapsulation - mechanism that binds together code and data in manipulates, and keeps both safe from outside interference and misuse. Inheritance - process by which one object acquires the properties of another object Polymorphism - one name many forms. &quot;one interface, multiple methods&quot;. Abstraction - technique of choosing common features of objects and methods is known as abstracting. It also involves with concealing the details and highlighting only the essential features of a particular object or a concept.
  • 8. Advantages of OOPs Simpler, easier to read programs More efficient reuse of code Faster time to market More robust, error-free code
  • 9. “ Write Once Run Anywhere” Programs are first written in plain text files ending with the .java extension. programs are compiled into the Java Virtual Machine (JVM) code called bytecode. File with .class extension Bytecode is machine-independent and can run on any machine that has JVM The byte code is easily interpreted and therefore can be executed on any platform having a JVM
  • 10. Robust , Secure No memory pointers Garbage collection -- no bad addresses Bounds checking Programs runs inside the virtual machine sandbox. Exception Handling
  • 11. Multithreading program’s capability to perform several tasks simultaneously e.g. downloading a video file while playing the video would be considered multithreading Multithreading is particularly useful in graphical user interface (GUI) and network programming.
  • 12. Java Components Java Virtual Machine. Java Application Programming Interface (API)
  • 13. Java Development Kit The Java Development Kit (JDK) is a Sun Microsystems product aimed at Java developers. Program development environment for writing Java applications It consists of a runtime environment that &quot;sits on top&quot; of the operating system layer as well as the tools and programming that developers need to compile, debug, and run applications written in the Java language.
  • 14. Installing Java Development Kit SMI -> Knowledge Base -> Installing JDK Article JDK Stored on path: c:\>Softwares
  • 15. HANDS On HANDS On
  • 16. CLASSPATH The CLASSPATH environment variable is used by Java to determine where to look for classes referenced by a program. In the CLASSPATH, you do not need to specify the location of normal java packages and classes such as java.util or java.io.IOException. Open the System Properties window (by right-clicking on My Computer and selecting Properties, or through the Control Panel - Start -> Control Panel -> System)
  • 17. CLASSPATH contd.. On the Advanced tab, click the Environment Variables button. On the Environment Variables windows, if a CLASSPATH variable is already defined, then select it and click Edit. If one is not defined, then click the New button. On the User Variable window, the variable name should be CLASSPATH. Set the value as appropriate. Note that different class file location values should be separated with a semicolon on a Windows machine.
  • 18. Object Data structures consisting of States (data fields) and behavior (methods) together with their interaction E.g. Dogs : State (name, color, breed ..) & Behavior (barking, fetching ..) object stores its state in fields (variables) and exposes its behavior through methods (functions) Methods operate on an object's state and serve as the primary mechanism for object-to-object communication
  • 19. Object contd.. class Bicycle { /*Fields, Variables */ int cadence = 0; /*integer DATA TYPE*/ int speed = 0; int gear = 1; /*Methods*/ void changeCadence(int newValue) { cadence = newValue; } void changeGear(int newValue) { gear = newValue; } void speedUp(int increment) { speed = speed + increment; } void applyBrakes(int decrement) { speed = speed - decrement; } }
  • 20. Class blueprint from which individual objects are created. this blueprint describes the state and behavior that the objects of the class all share. An object of a given class is called an instance of the class. Create Bicycle objects Bicycle bike1 = new Bicycle(); Bicycle bike2 = new Bicycle(); Invoke methods on those objects bike1.changeCadence(50); bike2.changeCadence(20);
  • 21. Elements of Java Literals - Any number, text, or other information that represents a value. Example int abc = 10; private static final int xyz = 25; Identifiers - Identifiers are the names of variables, methods, classes, packages and interfaces Datatype - Set of data with values having predefined characteristics and operators you can perform on them Keywords - Keywords are identifiers that cannot be use by end user as variable name Symbols - ; , / etc
  • 23. Java Keywords abstract, assert, boolean, break, byte, case, catch, char, class, const, continue, default, do, double, else, enum, extends, false, final, finally, float, for, goto, if, implements, import, instanceof, int, interface, long, native, new, null, package, private, protected, public, return, short, static, strictfp, super, switch, synchronized, this, throw, throws, transient, true, try, void, volatile, while
  • 24. Java Symbols ; Semi-colon indicates the end of a statement () Parentheses used in several places including: method, casting [] square brackets used in array declaration {} curly braces used to enclose the code of method // Indicates a single line comment /*..*/ comments that can span more than one line.
  • 25. Java Symbols contd.. : colon used in switch statements and in conditional operator. &quot; &quot; Double quotes surround a string literal. ' ' Single quotes surround a character literal. +,-,etc Operator symbols. ? Used with the conditional operator x = boolean ? y : z;
  • 26. HelloProfessor Program Open any TextEditor and write down the following program /* The HelloProfessor class implements an application that displays result to the standard output. */ public class HelloProfessor { /*visibility [final] [static][synchronize] dataType variable name [ = initialization value ]*/ public final static String ProfessorName = &quot;Type your name here&quot;; public String SMI = &quot;SMI&quot;; public HelloProfessor() { } /*Constructor*/ /*visibility [final] [static][synchronize] returnType methodName([parameterList])*/ public static void main(String args[]) { /*HelloProfessor Object*/ HelloProfessor helloProfessor = new HelloProfessor(); /*display result on Standard Output*/ System.out.println(&quot;Hello &quot;+HelloProfessor.ProfessorName); System.out.println(&quot;Welcome to Samsung University Program!!!&quot;); System.out.println(&quot;Welcome to &quot;+helloProfessor.SMI); } } Save file as HelloProfessor.java
  • 27. HelloProfessor Program Contd.. name of class is same as name of file ( .java extension) body of class surrounded by { } this class has one method called main. All Java applications must have a main method in one of the classes. execution starts here body of method within { } all other statements end with semicolon ;
  • 28. Compiling HelloProfessor Program Use compiler called javac which is provided by java. Go to the command prompt and type drive:\ > javac HelloProfessor.java javac compiler will create a class file called HelloProfessor.class that contains only bytecodes. These bytecodes have to be interpreted by a Java Virtual Machine(JVM) that will convert the bytecodes into machine codes.
  • 29. Running HelloProfessor Program Once we successfully compiled the program, we need to run the program in order to get the output. this can be done by the java interpreter called java. In the command line type as shown here. Go to the command prompt and type drive:\ > java HelloProfessor the output will be displayed as Hello Professor name
  • 30. Methods information needed to do their job methods break down large problems into smaller ones your program may call the same method many times saves writing and maintaining same code methods can take parameters methods can return a value. must specify type of value returned
  • 31. Method Signature visibility [static] returnType methodName(parameterList) visibility: public : accessible to other objects and classes protected : accessible to classes which inherit from this one private : accessible only to own class default : access only to classes within same package static keyword: use when method belongs to class as whole not object of the class
  • 32. Method Signature contd.. return type: specifies type of information returned. can be a simple data type int, float, double, char, String, boolean or a class if nothing returned, use keyword void method name parameterList: list of datatype , objects etc comma seperated list
  • 33. Variable Signature visibility [final] [static] datatype variableName visibility: public : accessible to other objects and classes protected : accessible to classes which inherit from this one private : accessible to own class default : access to classes within same package. static keyword: when method belongs to class as whole and not object final keyword: constant value that cannot be changed
  • 34. Application Structure [package packagename ;] [import packagename.classname ;] or [import packagename.*; ] [visibility] [abstract] [static] [final] class classname [implements interfacename ] [extends superclass ] OR [visibility] interface interfacename [extends interfacename ] { [ [visibility] [static] [final] [datatype varaible = initialization ;] ] [constructor] /*method without return type & method name same as classname*/ [ [visibility] [static] [final] [returnType] [ methodname ] ( [ parameterList ] ) { } ] }
  • 35. Application Structure contd.. public - indicates that the method can be called by any object static - indicates that the method is a class method, which can be called without the requirement to instantiate an object of the class void - indicates that the method doesn't return any value main(String args[]) - it's the entry point for your application and will subsequently invoke all the other methods required by your program.
  • 36. Constructor creates an Object of the class i.e. it initialize all instance variables and creates place in memory to hold the Object. Constructor name is the same as the class name Instead of a return type and a name, just use the class name Every class has a constructor to make its objects If you don’t define a constructor, a default one will be created. Sets all the fields of the new object to default value (if not provided) You can supply arguments
  • 37. Visibilty of variable / methods public: keyword applied to a class, makes it available/visible everywhere. Applied to a method or variable, completely visible. private: fields or methods for a class only visible within that class. Private members are not visible within subclasses, and are not inherited. protected: members of a class are visible within the class, subclasses and also within all classes that are in the same package as that class.
  • 38. Package Java’s way of grouping a number of related classes and/or interfaces together into a single unit. Programmers also typically use packages to organize classes belonging to the same category or providing similar functionality. The package statement must appear as the first statement in a file of Java source code, if it appears e.g. package abc; A package is the Java version of a library
  • 39. Benefits of Package The classes contained in the packages of other programs/applications can be reused. Resolves classname conflicts: two classes in two different packages can have the same name. If there is a naming clash, then classes can be accessed with their fully qualified name. Classes in packages can be hidden if we don’t want other packages to access them. Classes in the same package can access each other's package-access members.
  • 41. Import There are two ways of accessing the classes or class methods stored in packages: Using fully qualified class name java.lang.Math.sqrt(x); Import package and use class name directly. The import directive tells the compiler where to look for the class definitions when it comes upon a class. import java.lang.Math and then use Math.sqrt(x);
  • 42. Import contd.. Selected or all classes in packages can be imported: import package.class; or import package.*; By default Implicit in all programs: import java.lang.*; The general form of importing package is: import package1[.package2][…].[classname][.*]; Example: import myPackage.ClassA; or import myPackage.secondPackage.*;
  • 43. Operators & Control Flows Almost exactly like regular ANSI C. +, *, -, /, %, ++, --, +=, etc. ==, !=, >, < , etc. if statements, for loops, while loops, do loops, switch statements, etc. continue, break, return.
  • 44. Final classes , methods, variables Final class, why? - increase system security: disables creating a subclass of a class and then substituting for the original one - good object-oriented design: your class should have no subclasses Final methods, why? - To protect some of your class's methods from being overridden declare them final. Final variables, why? - Doesn’t allow to change the value of the variable.
  • 45. Constructor Invocation The constructors are called either explicitly or implicitly from base-class to sub-class down the inheritance hierarchy. The compiler forces invocation of base-class constructor as the first thing that happens in the sub-class constructor , this means you cannot catch any exception thrown in the base-class's constructor.
  • 46. Inheritance All Java classes are arranged in a hierarchy, starting with Object, which is the superclass of all Java classes Inheritance in OOP is analogous to inheritance in humans Inheritance and hierarchical organization allow you to capture the idea that one thing may be a refinement or extension of another Inheritance allows a software developer to derive a new class from an existing one, for the purpose of reuse, enhancement, adaptation, etc.
  • 47. Inheritance contd.. The existing class is called the parent class, or superclass, or base class The derived class is called the child class or subclass. As the name implies, the child inherits characteristics of the parent That is, the child class inherits the methods and data defined for the parent class. creates a IS-A relationship meaning child is a more specific version of parent.
  • 48. Class Hierarchy A child class of one parent can be the parent of another child, forming class hierarchies At the top of the hierarchy there’s a default class called Object .
  • 49. Extends In Java, we use the reserved word extends to establish an inheritance relationship. Multiple inheritance is not supported in java public class Parent { /* class contents */ int weight; public int getWeight() {…} } public class Child extends Parent { /* class contents */ public void write() {…} public int getWeight() {…} /* override */ public int getWeight(int abc) {…} /* overload */ }
  • 50. Overriding If a method in a subclass has the same name and type signature as a method in its superclass, then method in the subclass is said to override the method in superclass. The overriding method has the same name, number and type of parameters, and return type as the method it overrides. In java, all methods except of constructors can override the methods of their ancestor class. If a method is declared with final modifier, it cannot be overridden
  • 51. Overriding contd.. A subclass must override methods that are declared abstract in the superclass, or the subclass itself must be abstract. If a subclass defines a class method with the same signature as a class method in the superclass, the method in the subclass hides the one in the superclass. The access specifier for an overriding method can allow more, but not less, access than the overridden method. For example, a protected instance method in the superclass can be made public, but not private, in the subclass.
  • 52. Overriding vs Shadowing The distinction between shadowing and overriding has important implications. public class Animal { public static void hide() { System.out.println(&quot;The hide method in Animal.”); } public void override() { System.out.println(&quot;The override method in Animal.&quot;); } } public class Cat extends Animal { public static void hide() { System.out.println(&quot;The hide method in Cat.&quot;); } public void override() { System.out.println(&quot;The override method in Cat.&quot;); } public static void main(String[] args) { Animal animal = new Cat(); animal.hide(); animal.override(); } } Output: The hide method in Animal. The override method in Cat.
  • 53. Overriding access modifiers The access specifier for an overriding method can allow more, but not less, access than the overridden method. For example, a protected instance method in the superclass can be made public, but not private, in the subclass. You will get a compile-time error if you attempt to change an instance method in the superclass to a class method in the subclass, and vice versa.
  • 54. Overloading In Java it is possible to define two or more methods within the same class that share the same name, as long as their parameter declarations are different. When this is the case, the methods are said to be overloaded, and the process is referred to as method overloading. Method overloading is one of the ways that Java implements polymorphism.
  • 55. Overloading contd.. class Overloading { void test() { System.out.println(&quot;No parameters&quot;); } void test(int a, int b) { System.out.println(&quot;a and b: &quot; + a + &quot; &quot; + b); } void test(float a) { System.out.println(&quot;Inside test(double) a: &quot; + a); } } class Overload { public static void main(String args[]) { Overloading ob = new Overloading(); ob.test(); ob.test(10, 20); ob.test(123.2); } }
  • 56. “ this” “ this” is a reference to the current object — the object whose method or constructor is being called. You can refer to any member of the current object from within an instance method or a constructor by using this. Can be used with variables or methods or constructors.
  • 57. Using “this” with a Field The most common reason for using the this keyword is because a field is shadowed by a method or constructor parameter. public class Point { public int x = 0; public int y = 0; /* constructor */ public Point(int x, int y) { this.x = x; this.y = y; } } Each argument to the constructor shadows one of the object's fields - inside the constructor x is a local copy of the constructor's first argument. To refer to the Point field x, the constructor must use this.x.
  • 58. Using “this” with a Constructor From within a constructor, you can also use ‘this’ to call another constructor in the same class. Also called as explicit constructor invocation. public class Rectangle { private int x, y, width, height; public Rectangle(int width, int height) { this(0, 0, width, height); } public Rectangle(int x, int y, int width, int height) { this.x = x; this.y = y; this.width = width; this.height = height; } } Compiler determines which constructor to call, based on the number and type of arguments.
  • 59. “ super” refers to the superclass (base class) usage: with a variable or method (most common with a method) as a function inside a constructor of the subclass you can invoke the overridden method through the use of the keyword super can also use super to refer to a hidden field (not recommended)
  • 60. Accessing Superclass Members If your method overrides one of its superclass's methods, you can invoke the overridden method through the use of the keyword super. public class Superclass { public void printMethod() { System.out.println(&quot;Printed in Superclass.&quot;); } } Here is a subclass, called Subclass, that overrides printMethod(): public class Subclass extends Superclass { public void printMethod() { /*overrides printMethod in Superclass*/ super.printMethod(); System.out.println(&quot;Printed in Subclass&quot;); } }
  • 61. Accessing Superclass Constructor With super(), the super class no-argument constructor is called. With super(parameter list), the superclass constructor with a matching parameter list is called. class Employee { public Employee(String name, double salary) { …… } } class Manager extends Employee { private double bonus; public void setBonus(double bb) { …} public Manager ( String name, double salary, double bonus ) { super(name, salary); this.bonus = bonus; } }
  • 62. Abstract There are situations in which you will want to define a superclass that declares the structure of a given abstraction without providing a complete implementation of every method. Sometimes you will want to create a superclass that only defines a generalized form that will be shared by all of its subclasses, leaving it to each subclass to fill in the details. One way this situation can occur is when a superclass is unable to create a meaningful implementation for a method. Example consider Superclass figure in which area() cannot be implemented. The definition of area() is simply a placeholder. It will not compute and display the area of any type of object.
  • 63. Abstract contd.. you want some way to ensure that a subclass does, indeed, override all necessary methods. Java's solution to this problem is the abstract method. An abstract class is a class that is declared abstract - it may or may not include abstract methods Abstract classes cannot be instantiated, but can be subclassed. An abstract method is a method that is declared without an implementation (without braces, and followed by a semicolon), abstract type name(parameter-list); Any class that contains one or more abstract methods must also be declared abstract.
  • 64. Abstract contd.. When an abstract class is subclassed, the subclass usually provides implementations for all of the abstract methods in its parent class. However, if it does not, the subclass must also be declared abstract. Abstract classes can include as much implementation as they see fit. Although abstract classes cannot be used to instantiate objects, they can be used to create object references, because Java's approach to run-time polymorphism is implemented through the use of superclass references.
  • 65. Abstract contd.. /* Using abstract methods and classes.*/ abstract class Figure { double dim1, dim2; Figure(double a, double b) { dim1 = a; dim2 = b; } /* area is now an abstract method */ abstract double area(); } class Rectangle extends Figure { Rectangle(double a, double b) { super(a, b); } /* override area for rectangle*/ double area() { System.out.println(&quot;Inside Area for Rectangle.&quot;); return dim1 * dim2; } }
  • 66. Abstract contd.. class Triangle extends Figure { Triangle(double a, double b) { super(a, b); } /* override area for right triangle*/ double area() { System.out.println(&quot;Inside Area for Triangle.&quot;); return dim1 * dim2 / 2; } } class AbstractAreas { public static void main(String args[]) { // Figure f = new Figure(10, 10); /* illegal cannot be instantiated*/ Rectangle r = new Rectangle(9, 5); Triangle t = new Triangle(10, 8); Figure figref; /* this is OK, no object is created */ figref = r; System.out.println(&quot;Area is &quot; + figref.area()); figref = t; System.out.println(&quot;Area is &quot; + figref.area()); } }
  • 67. Interface In Java an interface is similar to an abstract class in that its members are not implemented. Interfaces are declared using the interface keyword, and may only contain method signatures and constant declarations (variable declarations that are declared to be both static and final). An interface may never contain method definitions. An interface may extend, any number of interfaces. As interfaces are implicitly abstract, they cannot be directly instantiated except when instantiated by a class that implements the said interface.
  • 68. Interface contd.. If your class claims to implement an interface, all methods defined by that interface must appear in its source code before the class to successfully compile. Interface can only be implemented by classes or extended by other interfaces. An interface may not implement an interface benefit of using interfaces is that they simulate multiple inheritance.
  • 69. Interface contd.. Defining an interface is similar to creating a new class: public interface OperateCar {  /*constant declarations, if any*/ int signalTurn(Direction direction, boolean signalOn); int getRadarFront(double distanceToCar, double speedOfCar); int getRadarRear(double distanceToCar, double speedOfCar); ...... /*more method signatures*/ } Note that the method signatures have no braces and are terminated with a semicolon.
  • 70. Polymorphism Polymorphism is a term that describes a situation where one name may refer to different methods. In java there are two type of polymorphism: overloading type and overriding type. When you override methods, java determines the proper methods to call at the program’s run time. Overriding occurs when a class method has the same name and signature as a method in parent class. Overloading occurs when several methods have same names with different method signature. Overloading is determined at the compile time.
  • 71. Encapsulation hiding information from unwanted outside access and attaching that information to only methods that need access to it. binds data and operations tightly together and separates them from external access that may corrupt them intentionally or unintentionally. Encapsulation is achieved by declaring variables, methods, class with access modifiers Providing access through the use of public accessor (getter) and mutator (setter) methods.
  • 72. Data Abstraction Data abstraction and encapsulation are closely tied together. simple definition of data abstraction is the development of classes, objects, types in terms of their interfaces and functionality, instead of their implementation details. Abstraction is used to manage complexity. Abstraction decompose complex systems into smaller components Implementation (Encapsulation) is the next step
  • 73. Threads Software that can do multiple things simultaneously is known as concurrent software. In concurrent programming, there are two basic units of execution: processes and threads. In the Java programming language, concurrent programming is mostly concerned with threads. However, processes are also important. A computer system normally has many active processes and threads. A thread is an independent path of execution within a program. Threads are sometimes called lightweight processes.
  • 74. Threads contd.. Threads exist within a process — every process has at least one. Threads share the process's resources, including memory and open files. Threads communicate via shared access to data JVM allows an application to have multiple threads of execution running concurrently. Multiple threads in process execute same program A Java program can have many threads, and these threads can run concurrently, either asynchronously or synchronously Every thread in Java is created and controlled by the java.lang.Thread class
  • 75. Threads contd.. Multithreading refers to two or more tasks executing concurrently within a single program. Advantages: - Threads are lightweight compared to processes - Threads share the same address space and therefore can share both data and code - Context switching between threads is usually less expensive than between processes - Cost of thread intercommunication is relatively low that that of process intercommunication - Threads allow different tasks to be performed concurrently.
  • 76. Creating Threads Two ways of creating threads: - implementing an Runnable interface - extending a Thread class.
  • 77. Runnable Interface Implementing Runnable Interface The Runnable Interface Signature public interface Runnable { void run(); } implement the Runnable Interface and then instantiate an object of the class. override the run() method into your class which is the only method that needs to be implemented. The run() method contains the logic of the thread.
  • 78. Runnable Interface contd.. class RunnableThread implements Runnable { Thread runner; public RunnableThread() { } public RunnableThread(String threadName) { runner = new Thread(this); /*(1) Create a new thread. */ runner.start(); /*(2) Start the thread. */ } public void run() { /*Display info about this particular thread*/ System.out.println(Thread.currentThread()); } }
  • 79. Thread Class Extending Thread class class XThread extends Thread { XThread() { } XThread(String threadName) { super(threadName); /*Initialize thread. */ System.out.println(this); start(); } public void run() { /*Display info about this particular thread */ System.out.println(Thread.currentThread().getName()); } }
  • 80. Exceptions An exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions. An exception is an object that enables a program to handle unusual/erroneous situations A method can throw an exception void doubleArray( int[] A) throws Exception { … if (Index >= A.length) throw new Exception( “array too small ” + Index) … }
  • 81. Exceptions contd.. Exception is a class, and all Exception-like objects should be subclasses of Exception.
  • 82. Extending Exception A method can throw several exceptions (each of which is a subclass of the Exception class) public void scaleArray( int[] A, int s) throws ArrayRangeException, IllegalArgumentException { … if (Index >= A.length) throw new ArrayRangeException( “array too small ” + Index) … } class ArrayRangeException must be a subclass of (predefined) class Exception, and one of its constructors takes a string argument class IllegalArgumentException is predefined
  • 83. Exception Propagation A (caller) method can deal with an exception thrown by the method it calls in 2 ways: caller method can ignore exception handling In this case the exception thrown by the called method will be “passed up” and (effectively) thrown by the caller method This exception propagation will continue until the main method which was an access point of the java code, which will throw an error to the user (and print its description in the console output)
  • 84. Exception Propagation contd.. Except if any of the methods along the caller/callee chain explicitly handles this exception. This breaks the chain of exception propagation, and after the exception is handled, the control returns to normal execution.
  • 85. Try Catch Statement The try/catch statement encloses some code and is used to handle errors and exceptions that might occur in that code. try { body-code /*code that might throw exception */ } catch (exception-classname variable-name) { handler-code } The variable-name specifies a name for a variable that will hold the exception object if the exception occurs. Finally, the handler-code contains the code to execute if the exception occurs
  • 86. Try Catch Statement contd.. It is possible to specify more than one exception handler in a try/catch statement. When an exception occurs, each handler is checked in order (i.e. top-down) and the handler that first matches is executed. try { ……… } catch(<exceptionclass_1> <obj1>) { /*statements to handle the exception*/   } catch(<exceptionclass_2> <obj2>) { /*statements to handle the exception*/   }
  • 87. Try Catch Statement contd.. When an exception is thrown, normal execution is suspended. The runtime system proceeds to find a matching catch block that can handle the exception. If no handler is found, then the exception is dealt with by the default exception handler at the top level. try { int num1 = 10; int num2 = 0; int[] intarr = {0,1,2,3,4}; res = num1 / num2; }catch (ArrayIndexOutOfBoundsException e) { System.out.println(&quot;Error…. Array is out of Bounds&quot;); }catch (ArithmeticException e) { System.out.println (&quot;Can't be divided by Zero&quot;); }
  • 88. Finally Statement The finally block always executes when the try block exits. This ensures that the finally block is executed even if an unexpected exception occurs. allows the programmer to avoid having cleanup code accidentally bypassed by a return, continue, or break. Putting cleanup code in a finally block is always a good practice, even when no exceptions are anticipated.
  • 89. Finally Statement contd.. try{ … }catch(Exception obj) { … }finally { … } The runtime system always executes the statements within the finally block regardless of what happens within the try block. So it's the perfect place to perform cleanup