Sie sind auf Seite 1von 91

Introduction to Java

Objective
To explain the philosophy behind the Java Language Design To familiarize the language constructs and core concepts Act as a kick-start course to help the learner pursue selfstudy going forward

Course Contents
1. Feel of Java

2. Language Basics
3. Classes and Objects 4. Inheritance, Interfaces and Abstract classes

5. Strings and Arrays


6. Exception Handling 7. Garbage Collection 8. Collections

Part I

Getting a feel of Java

Java Evolution
Created by James Gosling for Sun Microsystems in 1991

Motivation
The need for platform independent language that could be embedded in various consumer electronic products like toasters and refrigerators.

At about the same time, the World Wide Web and the Internet were gaining popularity and it needed a programming language

Java Language or Technology?

A Programming Language A Platform Virtual Machine Application Programming Interface (API)

Java The Language


public class MyProgram { public static void main(String [] args) { System.out.println(Hello World!); } }

Java The Platform

Hands-on

Compile & Run a Java Program Command-line (notepad, javac, java) IDE (Eclipse) Fixing compile-time errors

Anatomy of a Java program

Class Definition (reserved word, case sensitive)

Comments Method Definition

Command-line arguments

//This program prints out Hello World public class MyProgram { public static void main(String [] args) { System.out.println(Hello World!); } }
Access Modifier (public, private, protected, default) Blocks

Always remember
1. Your Java programs should end with the .java extension. 2. Filenames should match the name of your public class.
For e.g., Class Hello should be coded in Hello.java

3.There can be only one public class per file. A single source file can contain any number of non-public classes.

Part II

Language Basics

Lets Code
Program to calculate sum and average of 3 numbers
//This class will calculate the sum and average public class SumAndAvg { public static void main(String [] args) { SumAndAvg obj = new SumAndAvg (); obj.calculateSumAndAvg(5,10,12); } public void calculateSumAndAvg(int a,int b,int c) { int sum=0; double avg=0.0; sum = a+b+c; avg = sum / 3; System.out.println("Sum:"+sum+" Avg:"+avg); } }

Identifiers
Identifiers are tokens that represent names of variables, methods, classes, etc. E.g.: Hello, main, System, out. Identifiers must begin with either a letter, an underscore _, or a dollar sign $. Letters may be lower or upper case. Subsequent characters may use numbers 0 to 9. You cannot use Java reserved keywords (Keywords are predefined identifiers reserved by Java for a specific purpose) as identifier names

Reserved Keywords

Literals
Literals are tokens that do not change - they are constant.
For E.g.:

int sum = 0; double avg = 0.0; System.out.println("Sum: + sum + "Avg: + avg);

The different types of literals in Java are:


Integer Literals Floating-Point Literals

Boolean Literals
Character Literals String Literals

Primitive Data Types


Type
boolean char byte short

Contains
true or false Unicode character Signed integer Signed integer

Default
false \u0000 0 0

Size
1 bit 2 bytes 1byte 2 bytes

Range
NA \u0000 to \uFFFF -128 to 127 -32768 to 32767 -2147483648 to 2147483647

int

Signed integer

4 bytes

long

Signed integer

8 bytes

-9223372036854775808 to 9223372036854775807

float

IEEE 754 floating point

0.0

4 bytes

1.4E-45 to 3.4028235E+38 4.9E-324 to 1.7976931348623157E+3 08

double

IEEE 754 floating point

0.0

8 bytes

Arithmetic Operators

Note: When an integer and a floating-point number are used as operands to a single arithmetic operation, the result is a floating point. The integer is implicitly converted to a floating-point number before the operation takes place.

Increment & Decrement Operators

For e.g.: i=1;j=2; i++; //2 --j; //1 k = i++ + ++j; //?

Relational Operators

Logical Operators
&& and &
Name Logical AND Boolean Logical AND Logical OR Boolean Logical OR Operator && & || |

|| and |

Exclusive OR
Logical Not

^
!

XOR (^)

NOT (!)

Control Structures
Control structures allows us to change the ordering of how the statements in our
programs are executed

Two types of Control Structures decision control structures


allows us to select specific sections of code to be executed

repetition control structures


allows us to execute specific sections of the code a number of times

Decision Control (If..Then..)


public class Grade { public static void main( String[] args ) { double grade = 92.0; if( grade >= 90 ){ System.out.println( "Excellent!" ); } else if( (grade < 90) && (grade >= 80)){ System.out.println("Good job!" ); } else if( (grade < 80) && (grade >= 60)){ System.out.println("Study harder!" ); } else{ System.out.println("Sorry, you failed."); } } }

Decision Control (Switch..Case..)


public class Grade { public static void main( String[] args ) { int grade = 92; switch(grade){ case 100: System.out.println( "Excellent!" ); break; case 90: System.out.println("Good job!" ); break; case 80: System.out.println("Study harder!" ); break; default: System.out.println("Sorry, you failed."); } } } Note: Only integer and character expressions allowed

Repetition Control (while loop)


int x = 0; while (x<10) { System.out.println(x); x++; } //infinite loop while(true) System.out.println(hello);

//no loops // statement is not even executed while (false) System.out.println(hello);

Repetition Control (dowhile loop)


int x = 0; do { System.out.println(x); x++; }while (x<10);

//infinite loop do { System.out.println(hello); } while(true);

// statement is executed once do { System.out.println(hello); } while (false);

Repetition Control (for loop)


for(InitializationExpression;LoopCondition;StepExpression) { statement1; statement2; . . . } for(;;) { statement1; statement2; . . . }

for(int x = 0; x < 10; x++ ){ System.out.println(x); }

Branching Statements
unlabeled break: 1. break a) Labeled b) Unlabeled 2. continue a) Labeled b) Unlabeled for(int x = 0; x < 10; x++ ){ System.out.println(x); if (x % 5 == 0) break; }

1. return

labeled break:
searchLabel: for( int i=0; i<10; i++ ){ for( int j=0; j<i; j++ ){ if( i == j ){ break searchLabel; } } }

Part III

Classes and Objects

Procedural vs Object-Oriented
Procedural Programming

Object-Oriented Paradigm

Program flow in procedural fashion Difficult to maintain as programs get larger

Data was given first priority More easy mapping to real-world problems

Functions were given more priority


than data

Programmer can define his own


data-types Reusability

Objects

Objects in the physical world can easily be modeled as software objects using the properties as data and the behaviors as methods

Classes

Class can be thought of as a template, a prototype or a blueprint of an object is the fundamental structure in object-oriented programming Two types of class members: Fields (properties, variables) specify the data types defined by the class Methods (behavior) specify the operations

Classes and Objects

Classes provide the benefit of reusability. Software programmers can use a class over and over again to create many object instances.

Creation of Objects
To create an object instance of a class, we use the new operator.

For example, if you want to create an instance of the class String, we write the following code,
String str2 = new String(Hello world!);

or also equivalent to,


String str2 = "Hello";

String class is a special (and only) class you can create an instance without using new keyword as shown above

Why use Methods?


Methods contain behavior of a class (business logic)

The heart of effective problem solving is in problem decomposition.


We can do this in Java by creating methods to solve a specific part of the problem.

Taking a problem and breaking it into small, manageable pieces is critical to writing large programs.

Two types of Methods


Instance (non-static) methods

Should be called after object instance is created More common than static methods
Static methods

Should be called in the form of [ClassName].[methodName]

Method Types - Example


public class Student { String name; int marks; static int count = 0; public Student(String name, int marks){ this.name = name; this.marks = marks; count++; } // instance method public void printDetails() { System.out.println(Name: + name); System.out.println(Marks: + marks); } // static method public static int getStudentCount() { return count; } }

Parameter Passing
Pass-by-Value when a pass-by-value occurs, the method makes a copy of the value of the variable passed to the method. The method cannot accidentally modify the original argument even if it modifies the parameters during calculations. all primitive data types when passed to a method are pass-byvalue. Pass-by-Reference When a pass-by-reference occurs, the reference to an object is passed to the calling method. This means that, the method makes a copy of the reference of the variable passed to the method. However, unlike in pass-by-value, the method can modify the actual object that the reference is pointing to, since, although different references are used in the methods, the location of the data they are pointing to is the same.

Pass-by-Value

Pass-by-Reference

Inheritance - Interfaces and Abstract Classes

Part IV

What is Inheritance
Inheritance is the concept of a child class (sub class) automatically inheriting the variables and methods defined in its parent class (super class). A primary feature of object-oriented programming along with encapsulation and polymorphism

Why Inheritance?
Benefits of Inheritance in OOP : Reusability Once a behavior (method) is defined in a super class, that behavior is automatically inherited by all subclasses. Thus, you write a method only once and it can be used by all subclasses. Once a set of properties (fields) are defined in a super class, the same set of properties are inherited by all subclasses. A class and its children share common set of properties A subclass only needs to implement the differences between itself and the parent.

Object class
Object class is mother of all classes

In Java language, all classes are sub-classed (extended) from the Object super class Object class is the only class that does not have a parent Class
Defines and implements behavior common to all classes including the ones that you write clone(); equals(Object obj); getClass(); hashCode(); toString(); ..

extends keyword
public class Person { String name; String address; public Person() { System.out.println(Inside Person:Constructor); } } public class Student extends Person { String class; int marks; public Student(){ System.out.println(Inside Student:Constructor); } } A subclass inherits all of the public and protected members (fields or methods) of its parent, no matter what package the subclass is in When a sub-class is instantiated, constructor-chaining happens

super keyword
public class Person { String name; String address; public Person(String name) { System.out.println(Inside Person:Constructor); } } public class Student extends Person { String class; int marks; public Student(String name, int marks){ super(name); this.marks = marks; System.out.println(Inside Student:Constructor); } }

Note: The super() call must occur as the first statement in a constructor The super() call can only be used in a constructor (not in ordinary methods)

Overriding methods
public class Person { public String getName(){ System.out.println(Person: getName"); return name; } } public class Student extends Person { public String getName(){ System.out.println(Student: getName"); return name; } }

Student obj = new Student(); obj.getName(); //Student: getName

Polymorphism
Polymorphism in a Java program The ability of a reference variable to change behavior according to what object instance it is holding. This allows multiple objects of different subclasses to be treated as objects of a single super class, while automatically selecting the proper methods to apply to a particular object based on the subclass it belongs to Person p = new Person(); Student s = new Student(); Person ps = new Student(); p.getName(); //Person: getName s.getName(); //Student: getName ps.getName(); //Student: getName

Final classes and Methods


Final Classes Classes that cannot be extended To declare final classes, we write, public final Person{ . . . } Final Methods Methods that cannot be overridden To declare final methods, we write, public final String getName(){ . . . }

Abstract Methods & Class


Abstract Methods Methods that do not have implementation (body) // Note that there is no body public abstract void someMethod(); Abstract Class An abstract class is a class that contains one or more abstract methods An abstract class cannot instantiated // You will get a compile error on the following code MyAbstractClass a1 = new MyAbstractClass(); Another class (Concrete class) has to provide implementation of the abstract methods

Sample Abstract Class


public abstract class LivingThing { public void breath(){ System.out.println("Living Thing breathing..."); } public void eat(){ System.out.println("Living Thing eating..."); } /** * Abstract method walk() * We want this method to be implemented by a * Concrete class. */ public abstract void walk(); }

Extending an Abstract Class


When a concrete class extends the LivingThing abstract class, it must implement the abstract method walk(), or else, that subclass will also become an abstract class, and therefore cannot be instantiated. For example, public class Human extends LivingThing { public void walk(){ System.out.println("Human walks..."); } }

When to use?
Abstract methods are usually declared where two or more subclasses are expected to fulfill a similar role in different ways through different implementations (Polymorphism) These subclasses extend the same Abstract class and provide different implementations for the abstract methods Use abstract classes to define broad types of behaviors at the top of an object-oriented programming class hierarchy, and use its subclasses to provide implementation details of the abstract class.

What is an Interface?
It defines a standard and public way of specifying the behavior of classes Defines a contract All methods of an interface are abstract methods Defines the signatures of a set of methods, without the body (implementation of the methods) A concrete class must implement the interface (all the abstract methods of the Interface) It allows classes, regardless of their locations in the class hierarchy, to implement common behaviors

Example: Interface Employee


// // // // Note that Interface contains just set of method signatures without any implementations. No need to say abstract modifier for each method since it assumed.

public interface Employee {


public void getSalary(); public void fileTimeSheet( int days); public void applyforLeave( Object a, Object b);

Why Interface?
Reason #1 To reveal an object's programming interface (functionality of the object) without revealing its implementation

Reason #2 To have unrelated classes implement similar methods (behaviors) One class is not a sub-class of another
Reason #3 To model multiple inheritance - you want to impose multiple sets of behaviors to your class Each set is defined as an interface A class can implement multiple interfaces while it can extend only one class

Interface vs Abstract Class


All methods of an Interface are abstract methods while some methods of an Abstract class are abstract methods An interface can only define constants while abstract class can have fields Interfaces have no direct inherited relationship with any particular class, they are defined independently Interfaces themselves have inheritance relationship among themselves

Part V

Strings and Arrays

Concept of Strings
is a sequence of characters is immutable (once created and initialised cannot be changed) String class differs from other classes in that you can use + and += operators

How to create a String?


String greeting = Hello World; String greeting = new String(Hello World); char[] helloArray = { 'h', 'e', 'l', 'l', 'o', '.'}; String helloString = new String(helloArray);

String Methods

String Methods (contd..)

StringBuffer class
Problem with String objects: Once created, can no longer be modified (It is a final class) A StringBuffer object Similar to a String object But, mutable or can be modified Unlike String in this aspect Length and content may be changed through some method calls

StringBuffer Methods

Arrays Why?
Suppose we have here three variables of type int with different identifiers for each variable. int number1; int number2; int number3; number1 = 1; number2 = 2; number3 = 3;

As you can see, it seems like a tedious task in order to just initialize and use the variables especially if they are used for the same purpose.

Arrays What?
In Java and other programming languages, there is one capability wherein we can use one variable to store a list of data and manipulate them more efficiently. This type of variable is called an array. An array stores multiple data items of the same data type, in a contiguous block of memory, divided into a number of slots.

Arrays In Java
Declaring an Array int nums[]; int []nums; Instantiation int []nums; nums = new int[20]; int []nums = new int[20]; int []nums = {1,2,3,4,5};

Arrays Sample Code


public class ArraySample{ public static void main( String[] args ){ int[] nums = new int[100]; for( int i=0; i<100; i++ ){ nums[i] = i; } } } Note: Array index starts from 0 and not 1. So, its always from 0 to array-length 1.

Multidimensional Arrays
// integer array 512 x 128 elements int[][] twoD = new int[512][128];

// character array 8 x 16 x 24 char[][][] threeD = new char[8][16][24];

// integer array 4 rows x 2 columns int [][] arr42 = {{ 1,2 }, {3,4}, {5,6}, {7,8} };

// to access element of 3rd row and 2nd column int elt = arr42[2][1];

Part VI

Exception Handling

What is an Exception?
Exceptional event - typically an error that occurs during runtime Cause normal program flow to be disrupted Examples Divide by zero errors Accessing the elements of an array beyond its range Invalid input Hard disk crash Opening a non-existent file Heap memory exhausted

Exception Example
class DivByZero { public static void main(String args[]) { System.out.println(3/0); System.out.println(Pls. print me.); } }

Default Exception Handling


Displays this error message Exception in thread "main" java.lang.ArithmeticException: / by zero at DivByZero.main(DivByZero.java:3) Default exception handler Provided by Java runtime Prints out exception description Prints the stack trace Hierarchy of methods where the exception occurred Causes the program to terminate

What happens when an Exception occurs?


The runtime system searches the call stack for a method that contains an exception handler

Catching Exceptions

Syntax: try { <code to be monitored for exceptions> } catch (<ExceptionType1> <ObjName>) { <handler if ExceptionType1 occurs> } ... } catch (<ExceptionTypeN> <ObjName>) { <handler if ExceptionTypeN occurs> }

Catching Exceptions : Example

class DivByZero { public static void main(String args[]) { try { System.out.println(3/0); System.out.println(Please print me.); } catch (ArithmeticException exc) { //Division by zero is an ArithmeticException System.out.println(exc); } System.out.println(After exception.); } }

Catching Exceptions : finally

class DivByZero { public static void main(String args[]) { try { System.out.println(3/0); System.out.println(Please print me.); } catch (ArithmeticException exc) { //Division by zero is an ArithmeticException System.out.println(exc); } finally { //you cannot divide by zero System.out.println(You cannot divide 3 by 0. Pass another number); } System.out.println(After exception.); } } Contains the code for cleaning up after a try or a catch

Garbage Collection

Part VII

What is GC?
The Java virtual machine's heap stores all objects created by a running Java application. Objects are created by the program through new keyword, but never freed explicitly by the program > No need to call free(). Garbage collection is the process of automatically freeing objects that are no longer needed An object is determined to be no longer needed when there is no other object referencing to it

Advantages and Disadvantages


Advantages:
Programmer is free from memory management System cannot crash due to memory management Memory-leak is still possible, however - you can use memory profiler to find out where memory-leaking code is located

Disadvantages:
GC could add overhead GC can occur in an non-deterministic way

How does JVM perform GC?


The garbage collector must somehow determine which objects are no longer referenced and make available the heap space occupied by such unreferenced objects. The simplest and most crude scheme is to keep reference counter to each object There are many different schemes - years of research

GC API
finalize() method in Object class > Called by the garbage collector on an object when garbage collection determines that there are no more references to the object. gc() method in System class > Runs the garbage collector. > Calling the gc method suggests that the Java Virtual Machine expend effort toward recycling unused objects in order to make the memory they currently occupy available for quick reuse. > When control returns from the method call, the Java Virtual Machine has made a best effort to reclaim space from all discarded objects.

Collections

Part VIII

What is a collection?
A collection object sometimes called a container is simply an object that groups multiple elements into a single unit Collections are used to store, retrieve, manipulate, and communicate aggregate data

E.g. include Dictionary, Queue, Stack, etc.

Collections Framework
Interfaces: These are abstract data types that represent collections. Implementations: These are the concrete implementations of the collection interfaces. Algorithms: These are the methods that perform useful computations, such as searching and sorting, on objects that implement collection interfaces.

Interfaces

Collection Interface
public interface Collection extends Iterable { // Basic operations int size(); boolean isEmpty(); boolean contains(Object element); boolean add(E element); //optional boolean remove(Object element); //optional Iterator<E> iterator(); // Bulk operations boolean containsAll(Collection<?> c); boolean addAll(Collection<? extends E> c); //optional boolean removeAll(Collection<?> c); //optional boolean retainAll(Collection<?> c); //optional void clear(); //optional // Array operations Object[] toArray(); <T> T[] toArray(T[] a); }

Collections Interface

Interfaces

Implementations Hash table Resizable array Tree TreeSet ArrayList LinkedList Linked list Hash table + Linked list LinkedHashSet

Set List Queue Map

HashSet

HashMap

TreeMap

LinkedHashMap

Further Reading

Part IX

Topics not covered

Generics Threads I/O GUI Framework

References

http://www.javapassion.com/javaintro/ http://www.javabat.com http://java.sun.com/docs/books/tutorial/index.html http://java.sun.com/javase/technologies/index.jsp

Thank You

Das könnte Ihnen auch gefallen