Anda di halaman 1dari 69

Introduction to Java Programming

Session 3 Sukhjit Singh

Introduction to Java Programming

Goals
     

Session 3

Review Session 2 Decision Making Constructs Functions Loops Arrays Lab 2

Introduction to Java Programming

Review
    

Session 2

Variables Expression Input and Output Lab 1 Decision Making


 

Relational, Logical Operators If construct

Code for Guessing Game Problem

Introduction to Java Programming

Conditional Branching


Enable to branch the program execution, depending on whether a certain condition is met or not.
 

if statements switch statement

Introduction to Java Programming

if clause
  

Controls the flow of the execution of statements Two-way decision statement Evaluates the expression  depending on whether the value of expression is true or false; control is transferred to a particular statement.

Introduction to Java Programming

if clause


Implemented in different ways


if(test expression) statement; if(test expression) { block of statements; } statement;

Examples
if ( salary < 1000 ) salary = salary + 100; if (salary < 1000) { salary = salary + 100; }

Introduction to Java Programming

if


else clause

ifelse statement is an extension of simple if statement. General form of if..else statement is:
if(test expression is true) { block of statements } else { block of statements //if test expression // is false } statement;

Introduction to Java Programming

If

else clause

if there is only one statement, instead of block of statements


(test expression) statement; else statement; if

Introduction to Java Programming

if - else clause
Example:
int number; number = 27; if((number % 2) == 0) System.out.println("number is even"); else System.out.println("number is odd");

Introduction to Java Programming

else if clause
When multipath decisions are involved, multiple ifs are put together.
if(conditon1) { statement block1; } else if(condition2) { statement block2; } else { default statement block; } statement

Introduction to Java Programming

else if clause


Example
if(salary >= 10000) { bonus = salary * .2; } else if(salary >= 8000) { bonus=salary * .3; } else if(salary >= 6000) { bonus=salary * .5; } else { bonus=salary *.75; } System.out.println(" Bonus is : "+bonus

Introduction to Java Programming

Nesting if statements
if (salary >= 50000) { if (yearOfService > 5) { System.out.println(Eligible for Bonus); } else { System.out.println(Not eligible for service); } } // if else { System.out.println(Salary not greater than 50000); } // else

Introduction to Java Programming

switch clause
switch(test) { case value1: block of statements; break; case value2 : block of statements; break; .. default : default block; break; } statements;

Introduction to Java Programming

switch clause
Example: switch(choice) { case 1: System.out.println (Case 1); break; case 2 : System.out.println (Case 2); break; default : System.out.println (None of the cases); break; } //switch

Introduction to Java Programming

Methods in Java


Predefined Methods:


main() and println() System.out.println

User
  

Defined

Encapsulate few line of code under one name Reusable Divide and Conquer

Introduction to Java Programming

User-Defined Methods in Java




Provide a way to group a block of code and then refer to it by name. If a program is divided into functional parts, then each part may be independently coded and later combined into a single unit. These sub programs are called as methods Make the program easier to understand, test, debug and maintain. Saves time, memory, space

Introduction to Java Programming

Method Definition


Method definition consists of four parts:


 

 

Name of the method Type of object or primitive type the method returns A list of parameters The body of the method

Introduction to Java Programming

Method Return Type




 

If the method has a return type, you need to explicitly return a value inside the body of the method. For this return keyword is used. Methods in Java can return any valid Java type. This can be primitive data types, boolean, an array or an object.

Introduction to Java Programming

Method Prototype
Method's signature or prototype consists of:
 

Name of the method Type of object or primitive type the returns A list of parameters

method

For now all methods we create will be static.




Advantage: only one copy of the method will be stored and can be used without creating an object. (This will become more clear once we get to object theory.)

Introduction to Java Programming

Methods Definition
static int findLargest(int a, int b, int c) { int high = a; if (b > high) high = b; if (c > high) high = c; return high; }

Introduction to Java Programming

Method call


Refer to method name in the body of main() or another function.




Example
 

int highestval; highestval = findLargest(19, 12, 16);

In the above example,


 

findLargest is the method call. 19, 12 and 16 are args. a, b and c are parameters

static int findLargest(int a, int b, int c)




Introduction to Java Programming

Method Arguments and Parameters




The arguments and parameters have a 3 rules in their relationships




The value of arguments is passed to parameters The datatype of args. and parameters must match by position Number of args = Number of parameters

Introduction to Java Programming

Passing parameters by Value


When parameters are passed by value to a method, only a copy of the values of the actual arguments is passed into the called method.  This means that whatever occurs to these variables inside the method, will have no effect on the variables used in the actual argument list.  Primitive data types are passed by value


Introduction to Java Programming

Passing parameters by Value


public class swap { public static void main(String args[]) { int a = 10; int b = 20; s1 = new swap(); /* s1 is created here */ s1.swapping(a, b); }/* main method ends here */ } void swapping(int a, int b) {
int temp; temp = a; a = b; b = temp;

} }

Introduction to Java Programming

Passing parameters by Reference


When an object is passed as a parameter to a method, you are actually passing reference to that object rather than passing the object itself or the copy of the object. This means that whatever you do to those objects inside the method, will affect the original object as well. Examples Under Pass by Reference.


Introduction to Java Programming

Loops


Several lines of code can be executed iteratively.

Determinate Loops (Counter Controlled Loops




Used to repeat a block of statements, a particular number of times

Indeterminate Loops (Event Controlled Loops)




Loops that keep on repeating an operation, depending on the results obtained within the loop. Not executed a fixed number of times

Introduction to Java Programming

Loop Structure
 

Consists of a control statement and a body Control statement tests certain conditions and then directs the repeated execution of the statements contained in the body of the loop. Entry-controlled loop (Pre-Test)


Control conditions tested, before the start of the loop execution. If control condition is not satisfied, the loop never gets executed. Control condition tested at the end of the loop body. Even if the test condition is not satisfied, the loop gets executed at least once

Exit controlled loop: (Post-Test)




Introduction to Java Programming

Counter Controlled Loops


Looping process includes four steps:
  

Setting and initialization of the counter Execution of statements in the loop Test for specified condition for the execution of the loop Incrementing or decrementing the counter

Introduction to Java Programming

Event Controlled Loops


An entry-controlled and indeterminate loop:
 

Test condition is evaluated If test condition is true, then the body of the loop is executed. Body of the loop executes repeatedly, till the test condition becomes false Control is transferred out of the loop

Introduction to Java Programming

while Loop

General Syntax
while(test condition) { body of the loop }

Introduction to Java Programming

while Loop Example


import corejava.*; class whileEg { public static void main(String args[]) { int ans = 1; int count = 0; while(ans == 1) { count = count + 1; System.out.println(count is " + count); ans = Console.readInt(do you wish to continue, press 1 for yes); } } } //whileEg

Introduction to Java Programming

do while Loop
An exit-controlled and indeterminate loop:
 

Test condition is evaluated, after the loop body Even if the condition is false, the loop will get executed, at least once.

Introduction to Java Programming

do while Loop

General Syntax
do (test condition) { body of the loop } while (test condition);

Introduction to Java Programming

do while Loop Example


do { System.out.println("Employee Name :"+Emp_Name); System.out.println("Employee Salary :"+Emp_Sal); ans=Console.readInt(Type 1 if you wish to see the salary of the next employee); } while(ans=1);

Introduction to Java Programming

for loop

An entry-controlled, which provides a more concise control. General Syntax:


for (initialization; testcondition; incr/decrement) { body of the loop } `

Introduction to Java Programming

for loop Example


int arr[] = {12, 34, 56, 1, 43, 65, 2, 57, 24}; int i; i = arr.length; for(i = 0;i < arr.length; i++) /* this loop will display all the elements of the array arr */ { System.out.println(arr[i]); }

Introduction to Java Programming

Lab 2 Discussion


On Discussion Thread

Arrays Searching and Sorting


Session 3 Sukhjit Singh

Introduction to Java Programming

Arrays


 

An array is a group of related data items that share a common name. Individual values in an array are referred to as elements. Array can be of any variable type. An item can be referred in an array, by using index number.

Introduction to Java Programming

Arrays


Arrays help in developing short and concise programs. Examples of arrays in Java:
int numbers[ ]; char[ ] letters; String [ ] names;

Introduction to Java Programming

Declaring an Array
 

An array variable is created to hold the array elements. Array variable is declared just like any other variable except that empty brackets i.e. [ ] are used while declaring an array. Array variable declarations:
int score[ ]; float temp[ ]; String names[ ];

Introduction to Java Programming

Creating Array Objects




Java does not allow to specify a number between the empty square brackets to represent number of items in the array. To create array objects,
num1 = new int[3];

When an array object is created, using new operator, all the slots of the array are initialized


0 for numeric arrays, false for boolean, '\0' for character arrays and null for objects.

Introduction to Java Programming

Creating Array Objects




Can also create array objects, with values initialized in the array:
int num1[ ] = { 2, 34, 29, 10 };

All the elements inside the braces must be of same type, as the variable that holds the array. In this type of declaration, an array of the size of number of elements included will be automatically created.

Introduction to Java Programming

Accessing Array Elements




To access an initial value stored in an array, the index number or the subscript of that array element has to be used:
ArrayName[subscript];

Array subscript starts with 0




String[ ] Name = new String[100]; means Name is an array that has 100 slots for storing 100 strings. These strings can be accessed using the subscript from 0 to 99.

Introduction to Java Programming

Assigning values to array elements




To assign a value to an array element, the index number or the subscript of that array element has to be used:
Name[0] = Becky"; Name[1] = Max"; Name[2] = Jim"; Name[99] = John ;

..

Introduction to Java Programming

Assigning values to array elements




To avoid accidentally overrunning the end of the array in the program, you can test the length of the array, by using the length instance variable
int len = Name.length;

Introduction to Java Programming

One-dimensional array


One-dimensional array is a list of items represented in the form of an array that has only one subscript. For example,
Name[0] = Becky;

Introduction to Java Programming

One-dimensional array
class ArrayDemo { public static void main(String args[]) { int[] num; int i; num = new int[4]; num[0] = 20; num[1] = 2; System.out.println(" Numbers in array are num[0] + + num [1]); } }

"+

Introduction to Java Programming

Multi-dimensional array
 

Used to store a table of values. Declaring a two-dimensional array:


type array_name[ ][ ];

For example, if we have to store Score1 and Score2 of 4 students, it can be done by:
Student = new int[4][2];

Introduction to Java Programming

Multi-dimensional array
class ArrayDemo { public static void main(String args[]) { int[][] Student; Student = new int[4][2]; //First student test score Student[0][0] = 20; Student[0][1] = 2; System.out.println(" Score1 of Student1 is: " + Student[0][0]); System.out.println(" Score2 of Student1 is: " + Student[0][1]); } }

Introduction to Java Programming

Arrays Passed as Arguments to Methods


 

Arrays are passed by reference to the methods. This means that changes that occur to the array inside the function, affect the original array.

Introduction to Java Programming

Arrays Passed as Arguments to Methods


class ArrDemo { public static void main(String args[]) { int arr[] = {1, 6, 3, 1, 0, 1, 34, 1}; ArrDemo pr = new ArrDemo( ); for(int i = 0; i < arr.length; i++) { System.out.println(arr[i]); } pr.PassArr(arr); System.out.println(New array is "); for(int i = 0; i < arr.length; i++) { System.out.println(arr[i]); } } //continued

Introduction to Java Programming

Arrays Passed as Arguments to Methods


void PassArr(int arr[]) { for(int i = 0; i < arr.length; i++) { if(arr[i] == 1) { arr[i] = 0; } //if } //for } //PassArr method } //class ArrDemo

Introduction to Java Programming

Searching
 

Sequential Search Binary Search

Introduction to Java Programming

Sequential Search
  

Used if list is not ordered or not sorted This search algorithm is very slow. The list is traversed, till an item is found or till the end of the list.

Introduction to Java Programming

Sequential Search
//Code for sequential search //target and locn is of found item int looker = 0; while ( looker < last && target != list[looker] ) looker++ ; locn = looker ; return ( target == list[looker] ) ;

Introduction to Java Programming

Binary Search
 

Used if the list is ordered or sorted Binary search starts off by testing data in the middle of the array. This determines if the target is in the first half or the second half of the array. Whichever half has the element is checked again. The half in which the element does not exist need not be tested again. Repeat the process till element is found.

Introduction to Java Programming

Binary Search


Three variable are required for binary search:


  

beginning of the list middle of the list end of the list.

Introduction to Java Programming

Binary Search
int first = 0; int mid ; int last ; while ( first <= last ) { mid = ( first + last ) / 2 ; if ( target > list[ mid ] )
first = mid + 1 ; /* look in upper half else if ( target < list[ mid ] )
*/

last = mid - 1 ; else first = last + 1 ; } locn = mid ; return (target == list [mid]);

Introduction to Java Programming

Sorting
  

Insertion Sort Bubble Sort Selection Sort

Introduction to Java Programming

Insertion Sort


The array is divided into two parts: sorted and unsorted. In each pass the first element of the unsorted sublist is picked and transferred into the sorted sublist by inserting it at the appropriate place. It will take n-1 passes to sort an array of size n.

Introduction to Java Programming

Insertion Sort
public void insertionSort (int[] list, int last ) { /*Local Declarations*/ int current ; /*Statements*/ for ( current = 1 ; current <= last ; current++) insertOne( list, current) ; return ; } //contd.

Introduction to Java Programming

Insertion Sort
void insertOne (int[] list, int current ) { int walker; int located; int temp ; located = FALSE ; temp = list[current] ; for (walker=current-1; walker >= 0 && !located;) if (temp < list[ walker ]) { list[walker + 1] = list[walker]; walker--;} else located = TRUE; list [ walker + 1 ] = temp ;}

Introduction to Java Programming

Bubble Sort


Using a for loop the lowest element is bubbled to the beginning of the unsorted segment of the array. Accomplished by a function called bubbleUp - makes one pass through the data.


Whenever it finds two elements out of sequence, it exchanges them. It then continues with the next element. This allows smallest number to be bubbled to the beginning of the array, while at the same time adjacent elements along the way are rearranged.

Introduction to Java Programming

Bubble Sort
void bubbleUp (int[] list, int current, int last) { int walker ; int temp ; for ( walker = last ; walker > current ; walker- ) if (list[ walker ] < list[walker - 1]) { temp = list[walker] ; list[walker] = list[walker - 1] ; list[walker - 1] = temp ; }//if return ; }// bubbleUp

Introduction to Java Programming

Selection Sort


List is divided into sublists, sorted or unsorted, which are divided by an imaginary wall. Find the smallest element from the unsorted sublist and swap it with the element in the beginning of the unsorted list. After each selection the wall between the sublist moves one element ahead, increasing the number in the sorted list and decreasing the number in the unsorted list. Each time we move one element from the unsorted list to the sorted list, it completes a sort pass. n-1 passes for sorting an array of n elements.

Introduction to Java Programming

Selection Sort
public void selectionSort (int[] list, int last ) { /*Local Declarations*/ int current ; /*Statements*/ for ( current = 0 ; current < last ; current++ ) exchangeSmallest ( list, current, last ) ; return ; } /*selectionSort*/

Introduction to Java Programming

Selection Sort
void exchangeSmallest(int[] list, int current, int last) { int walker; int smallest; int tempData; smallest = current; for (walker = current + 1 ; walker <= last ; walker++) //Smallest selected: exchange with current element if ( list[ walker ] < list[ smallest ] ) smallest = walker ; tempData = list[ current ] ; list[current] = list[ smallest ] ; list[smallest] = tempData ; return ; }// exchangeSmallest

Introduction to Java Programming

Lab 3 Discussion


On Discussion Thread

Anda mungkin juga menyukai