Introduction to Java | Class (Computer Programming) | Method (Computer Programming)

Introduction to Java

• 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 .

• At about the same time. the World Wide Web and the Internet were gaining popularity and it needed a programming language .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.

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 .

java)  IDE (Eclipse) • Fixing compile-time errors .Hands-on • Compile & Run a Java Program  Command-line (notepad. javac.

case sensitive) Comments Method Definition Command-line arguments //This program prints out Hello World public class MyProgram { public static void main(String [] args) { System. private.Anatomy of a Java program Class Definition (reserved word. } } Access Modifier (public.out.println(“Hello World!”). protected. default) Blocks .

Class Hello should be coded in Hello. 2.Always remember 1.There can be only one public class per file. A single source file can contain any number of non-public classes. . Your Java programs should end with the .g. For e.. Filenames should match the name of your public 3.

Part II Language Basics .

calculateSumAndAvg( c) { int sum=0.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 ().println("Sum:"+sum+" Avg:"+avg) b. avg = sum / 3.12). } public void calculateSumAndAvg(int a.out. double avg=0.10. sum = a+b+c. System. } } . obj.

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

Reserved Keywords .

g.0.Literals Literals are tokens that do not change . For E.out. The different types of literals in Java are: • Integer Literals • Floating-Point Literals • Boolean Literals • Character Literals • String Literals . double avg = 0.println("Sum:” + sum + "Avg:” + avg). System.they are constant.: int sum = 0.

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 0 4 bytes long Signed integer 0 8 bytes -9223372036854775808 to 9223372036854775807 float IEEE 754 floating point 0.4E-45 to ±3.0 4 bytes ±1.0 8 bytes .7976931348623157E+3 08 double IEEE 754 floating point 0.9E-324 to ±1.4028235E+38 ±4.

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

Increment & Decrement Operators For e. i++.: i=1. //? .g.j=2. //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 .

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

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

println(“hello”).println(“hello”). x++.out. } //infinite loop while(true) System.out.out. .Repetition Control (while loop) int x = 0.println(x). //no loops // statement is not even executed while (false) System. while (x<10) { System.

out. // statement is executed once do { System. } while (false).out.println(“hello”). do { System.println(x). . } while(true). x++.out. }while (x<10).println(“hello”).Repetition Control (do…while loop) int x = 0. //infinite loop do { System.

.) { statement1. . statement2. . .Repetition Control (for loop) for(InitializationExpression.println(x). } for(. x < 10. .out. . . x++ ){ System.LoopCondition. } for(int x = 0.StepExpression) { statement1. statement2. } .

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

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.

we write the following code. ● For example. String str2 = "Hello". or also equivalent to. String str2 = new String(“Hello world!”). we use the new operator. ● String class is a special (and only) class you can create an instance without using new keyword as shown above .Creation of Objects ● To create an object instance of a class. if you want to create an instance of the class String.

. – Taking a problem and breaking it into small. – We can do this in Java by creating methods to solve a specific part of the problem. manageable pieces is critical to writing large programs.Why use Methods? ● Methods contain behavior of a class (business logic) – The heart of effective problem solving is in problem decomposition.

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] .

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

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

Pass-by-Value .

Pass-by-Reference .

Interfaces and Abstract Classes Part IV .Inheritance .

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. – Once a set of properties (fields) are defined in a super class. the same set of properties are inherited by all subclasses. that behavior is automatically 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. you write a method only once and it can be used by all subclasses. Thus.

. hashCode().Object class ● Object class is mother of all classes – In Java language. toString(). . equals(Object obj). …. getClass(). 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().

} } public class Student extends Person { String class.out. } } ● 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.out. int marks. String address.println(“Inside Person:Constructor”). public Student(){ System.extends keyword public class Person { String name.println(“Inside Student:Constructor”). constructor-chaining happens . public Person() { System.

int marks){ super(name). } } public class Student extends Person { String class.println(“Inside Person:Constructor”). public Person(String name) { System. } } 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) . System. this.out.println(“Inside Student:Constructor”).marks = marks. public Student(String name.out.super keyword public class Person { String name. String address. int marks.

getName().out.println(“Person: getName"). obj. return name. } } public class Student extends Person { public String getName(){ System.Overriding methods public class Person { public String getName(){ System. //Student: getName .println(“Student: getName").out. return name. } } Student obj = new Student().

//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.getName().getName(). while automatically selecting the proper methods to apply to a particular object based on the subclass it belongs to Person p = new Person().getName(). //Student: getName ps. p. Person ps = new Student(). Student s = new Student(). //Person: getName s. – This allows multiple objects of different subclasses to be treated as objects of a single super class.

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

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..."); } }

. and use its subclasses to provide implementation details of the abstract class.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.

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 .

. String greeting = new String(“Hello World”). 'l'. String helloString = new String(helloArray). 'o'.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”. '. 'e'. char[] helloArray = { 'h'. 'l'.'}.

String Methods .

) ..String Methods (contd.

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

StringBuffer Methods .

number1 = 1. 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. int number3. .Arrays – Why? Suppose we have here three variables of type int with different identifiers for each variable. int number1. int number2. number2 = 2. number3 = 3.

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

5}.4. • Instantiation int []nums. int []nums = {1. nums = new int[20]. int []nums = new int[20].Arrays – In Java • Declaring an Array int nums[].2.3. . int []nums.

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

{7.Multidimensional Arrays // integer array 512 x 128 elements int[][] twoD = new int[512][128]. . // to access element of 3rd row and 2nd column int elt = arr42[2][1]. {5. // character array 8 x 16 x 24 char[][][] threeD = new char[8][16][24]. // integer array 4 rows x 2 columns int [][] arr42 = {{ 1.4}.8} }.6}. {3.2 }.

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 .

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

lang.ArithmeticException: / by zero at DivByZero.main( • 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 .Default Exception Handling • Displays this error message Exception in thread "main" java.

What happens when an Exception occurs? The runtime system searches the call stack for a method that contains an exception handler .

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

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

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

Garbage Collection Part VII .

• 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 . • Objects are created by the program through new keyword. but never freed explicitly by the program > No need to call free().What is GC? • The Java virtual machine's heap stores all objects created by a running Java application.

Advantages and Disadvantages Advantages: • Programmer is free from memory management • System cannot crash due to memory management • Memory-leak is still 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 . however .

years of research . • The simplest and most crude scheme is to keep reference counter to each object • There are many different schemes .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.

> 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. . • gc() method in System class > Runs the garbage collector.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.

Collections Part VIII .

. manipulate. Stack. include Dictionary. and communicate aggregate data E.g. retrieve. etc. Queue.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.

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

Interfaces .

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

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 .

html •http://java.sun.jsp •http://www.References • •http://java.

Thank You .

Sign up to vote on this title
UsefulNot useful