Java Professional Certificate Day 1- Bridge Session 1
Java - An Introduction Basic Features and Concepts Java - The new programming language from Sun Microsystems Java -Allows anyone to publish a web page with Java code in it Java - CPU Independent language Oak -The predecessor of Java
Java Features Now owned by Oracle Object Oriented Portable Architecture Neutral Distributed Multi-threaded Robust, Secure/Safe Interpreted High Performance Basic Features and Concepts
Java Virtual Machine Basic Features and Concepts JVM is an abstract machine. Provides special environment to execute Java byte code. a software residing on hardware and operating system. Compiler Compiler Source Code Byte Code Interpreter Hello World Hello.java Hello.class Output JVM
Java Technology Architecture Java Source Code Basic Features and Concepts Java Compiler Java Classes Java Runtime Environment Runtime Support Standard Library Classes Java Virtual Machine Java Plug-in Browser Operating System Hardware
Java Development tools Basic Features and Concepts java : Java Interpreter - runs the application. javac : Java compiler - converts source code to byte code. javadoc : creates HTML documents from java code used for creating documentation of the program. jdb : Java debugger, helps to fix errors in a program. javah: It produces header files. jar : A tool to make zipped files that are also Known as jar files(java Archive Files) Appletviewer : Helps to view and run applets.
Installation Demo Eclipse Learn how to install and use Eclipse
What is Eclipse? Eclipse It s an IDE(Integrated Development Environment) A software development kit (SDK) that includes the Java development tools. A Java-based application that requires a Java runtime environment (JRE) OR Java development kit(jdk) in order to run.
Create a program Basic Features and Concepts Using Notepad or another text editor, create a small Java file with the following text: public class HelloWorld public static void main(string[] args) System.out.println("Hello, World!"); Save this file as HelloWorld.java at a desired location. main is an essential method that must be present to run a java program
Classes & Objects OOP Concepts A class is a blueprint or prototype from which objects are created. Each object is said to be an instance of a particular class. public class Employee String name; String department; bonus()... Class Example
Objects OOP Concepts Structuresthat contain both data and methods Employeeclass used to create twoobjects : emp1, emp2 below Employee class Object Object emp1 emp2 Data for emp1 emp1.name emp1.department emp2.name emp2.department Data for emp2 object Method (behavior) for emp1 emp1.bonus() emp2.bonus() Method (behavior) for emp2
Four OOP Principles OOP Concepts Data Abstraction Encapsulation Inheritance Polymorphism
Data Abstraction OOP Concepts Act of representing essential features without including the background details or explanations Eg., a sort() method within a class presents sorted data to the outside world and hides the implementation details (algorithm) that may change over time
Encapsulation OOP Concepts Most striking feature of a class. Wrapping up of data and methods into a single unit (called class). It makes objects to be treated like black boxes.
Inheritance OOP Concepts A process by which object of one class acquires the properties of another class (like a son child inheriting traits of mother) Parent class is called Superclass. Child class is known as subclass.
Inheritance OOP Concepts Employee Name, Emp_id, etc printinfo() tax() etc Super Class regular contractor daily_wage Name, Emp_id, etc paid_leaves annual_bonus () Name, Emp_id, etc contracted_hours compute_salary() etc Name, Emp_id, etc daily_rate compute_wage() Sub Classes
Polymorphism OOP Concepts Ability totake same name but more than one form. allowsobjects to share different internal structure but same external structure. It is extensively used in implementing inheritance. Single function name can be used to handle different types and different number of arguments.
Polymorphism OOP Concepts Employee printinfo() regular contractor daily_wage printinfo(salary) printinfo(hours) printinfo(rate)
Java Program Structure Program Structure Documentation Section Package Statement Import Statements Interface Statements Class Definitions Main Method class Main Method Definition Suggested Optional Optional Optional Essential Essential
Java Tokens Tokens The smallest individual unit in a program is known as token.
Data Types Data Types Data types specify the size and type of values to be stored. Java language is rich in data types. Data types in Java Primitive (built-in) Non-Primitive (Derived)
Primitive Data Types Data Types Primitive Numeric Non-Numeric Integers Floatingpoint Character Boolean
Variables Variables It is an identifier. Basic unit of storage. It defines scope and a lifetime. Variable names may consist : Ø alphabets Ø digits, Ø underscore (_) Ø dollar sign($)
Type Conversion Variables Process of converting one primitive type to another. Type conversion Implicit Conversion Explicit Conversion
Implicit Conversion Variables Assigning one type of data to another type is Automatic Conversion. Conversion done by Java complier. Two conditions: 1. Two types are compatible. 2. The destination type is larger than source type. Also called Widening conversion. Assigning a smaller type to larger type is called widening.
Examples Variables Implicit Conversion int a = 5; double b = a; int double (4 Bytes) (8 bytes) Explicit Conversion long a =500; int b = (int) a; long int (8 Bytes) (4 bytes)
Example 1 Variables Class Example1 public static void main(string args[]) System.out.println("Variables created "); int i= 1234; long l= 12345678; float f1 =3.1242f; System.out.println( " i : " + i); System.out.println( " l : " + l); System.out.println( " f1 : " + f1); System.out.println(" "); System.out.println( " Type Conversion"); float m=(float)l; int f2=(int)f1; System.out.println( " (float)l : " + m); System.out.println( " (int)f1 : " + f2);
Output Variables Variables created i : 1234 l : 12345678 f1 : 3.1242 Type Conversion (float)l : 1.2345678E7 (int)f1 : 3
Control Statements Control Statements Programming languages use control statements. Handles the flow of execution. To advance and branch based on state of a program. Selection Statements Allows to choose different paths of execution based upon the outcome of expression. If Switch Control flow Iteration Statements Repeats one or more statements during program execution. While Do-while For Jump Statements Allows program to execute in a non-linear manner. Break Continue Retun
Class Fundamentals Classes and Methods Attributes Behavior Data that differentiates one object from another Defined by: Instance variables aka object variables define attributes of one particular object Class Variables define attributes of entire class one value for all objects Things that class of objects can do Eg. change attributes of an object receive information from other objects send messages to other objects
General form of a class Classes and Methods class Class_name type variable1; type variable2; Instance variables type methodname1(parameter-list) body of the method type methodname2(parameter-list) body of the method methods Members
A Simple Class class Employee int empid; String name; String dept; Class name Instance variables Classes and Methods
Declaring Objects Two-step process: Classes and Objects 1. Declare a variable of class type. Employee emp; 2. Acquire an actual physical copy of the object and assign it to that variable. emp = new Employee(); Combining above steps: Employee emp = new Employee();
new Operator Dynamically allocates memory for an object. Classes and Objects Statement Employee emp; Effect null emp emp = new Employee(); emp empid name dept Employee Object
Assigning Object Reference Employee emp1 = new Employee ; Classes and Objects Employee emp2 = emp1; emp1 empid name dept emp2 Employee Object
Creating Object: Example 2 class Employee int empid; String name; String dept; void display( ) System.out.println("Employee Id:" + empid); System.out.println("Name : " + name); System.out.println("Department : " + dept); A dot operator links the name of an object with instance variable. public class Employee_trial public static void main(string[] args) Employee emp1= new Employee(); emp1.empid = 001; emp1.name = "John"; emp1.dept = "Production"; Classes and Objects emp1.display( );
Methods: Example 3 Classes and Objects class Employee int empid; String name; String dept; void display( ) System.out.println( Employee Id: + empid); System.out.println( Name : + name); System.out.println( Department : + dept); Employee emp2= new Employee(); emp2.empid = 002; emp2.name = Deep"; emp2.dept = IT"; emp2.display( );
Types Constructors Constructors Parameterized Receive Parameters Non Parameterized Cannot receive any Parameters
Parameterized Constructor Example 4 Constructors class Employee int empid; String name; String dept; public Employee(int i, String n, String d) empid = i; name = n; dept = d; Constructor is a method with the same name as the class name. Sets values automatically for a new object public static void main(string[] args) Employee e1=new Employee(001, "John", "Production"); Employee e2=new Employee(); //Invalid
Non-parameterized Constructor Constructors Also called default Constructor. In a class with no explicit constructor,compiler 1. Supplies a default constructor. 2. Initializes the data members with any dummy value.
Example 5 Constructors public class Employee int empid; String name; String dept; public Employee() empid =0; name =" "; dept =" "; // Constructor public class Employee_trial public static void main(string[] args) Employee e1=new Employee();
Inheritance basics Inheritance The syntax of defining a derived/ subclass: Example class <sub class-name> extends <super class-name> body of class class salaried_employee extends Employee body of class
Member Access Inheritance Access control of inherited members: Access Specifier private public protected default Description Members are accessible only inside their own class and nowhere else Accessible in all the sub classes and class in the same package Accessible in their own class and subclasses regardless whether subclasses exist in the same package or other package. Accessible in the class with in the same package
Example public class Employee int empid; String name; String dept; public Employee() empid=0; name="null"; dept="null"; public Employee(int i, String n, String d) empid=i; name=n; dept=d; void show( ) System.out.println("Employee Id: " + empid); System.out.println("Name : " + name); System.out.println("Department : " + dept); Inheritance 44
Example- Inherited class Inheritance public class Salaried_Employee extends Employee int no_of_days; Salaried_Employee(int i, String n, String d, int num) empid=i; name=n; dept=d; no_of_days=num;
Packages Packages Containers for class. Keep the class name space compartmentalized. Provides naming and visibility control mechanism. Stored in a hierarchical manner. Explicitly imported into new class definitions. java.lang is the default package. 46
Definition Packages Include a package command as the first statement in a Java Source file. General form: package Mypackage; Above statement defines a namespace in which classes are stored. Name of the package All the standard java classes included with Java are stored in a package called java.
Example Packages Creating two packages: package Mypack; public class first public static void main(string[] args) System.out.println("Welcome to Package"); package Newpackage; public class Second public void msg() System.out.println("Hello World"); 48
Accessing Packages Packages import package.*; import package.classname; Fully qualified name
Interfaces: Introduction Interfaces Similar to a class in Java. Lack instance variables. Methods are declared without any body. An interface contains behavioursthat a class implements. interface A void show(); 50
Contd.. Interfaces Once defined, any number of classes can implement one interface. One class can implement any number of interfaces. Java implements One interface,multiple methods Polymorphism. class B implements A void show() //method body 51
Interfaces Interfaces No default implementation of any method specified within any interface. Variablescan bedeclared insideof interfacedeclarationswith final and static keyword. All the methods and variables are implicitly public. Class that includes an interface must implement all of the methods but not variables. Variablesmust be initialized withinan interface. 52
Interface Features Interfaces An interface can contain any number of methods. An interface is written in a file with a.java extension, with the name of the interface matching the name of the file. The byte code of an interface appears in a.class file. Interfaces appear in packages, and their corresponding byte code file must be in a directory structure that matches the package name. 53
Interface Interfaces You cannot instantiatean interface. An interface does not contain any constructors. All of the methods in an interface are abstract. An interface cannot contain instance fields. The only fields that can appear in an interface must bedeclared both static and final. An interface is not extended by a class; it is implemented by a class. An interface can extend multiple interfaces. 54
Defining Interfaces General form of an interface Access-specifier interface name return-type method-name1(parameter-list); return-type method-name2(parameter-list); type final-varname1=value; type final-varname2=value; Case1 : No access specifier Then default access and the interface is available to other members of the package. Case2 : public access Interface can be used by any other code. 55
Example Interfaces Defining an interface interface Callback void call(int param); 56
Implementation Interfaces Include the implements clause in the class definition. General form: class classname implements interface1[,interface2]] //class body In case of more than one interface,the interfaces are separated with a comma.
Example Interfaces Declaring a class implementing Callback interface. class Client implements Callback public void call(int p) System.out.println( Callback called with + p);