Java An Introduction Programming language developed by Sun
Java – An Introduction • Programming language developed by Sun Microsystems in 1991. • Originally called Oak by James Gosling • Originally created for consumer electronics ( TV, VCR, Mobile Phone, etc. ) • Internet and Web was just emerging, so Sun turned it into a language of Internet Programming. • Pure Object oriented language • Java is a whole platform, with a huge library, containing lots of reusable code, and an execution environment that provides services such as § security § portability across operating systems § automatic garbage collection. 1
Need for Java • Many different types of controllers with different set of CPU are used in electronic devices. • The problem with C and C++ is that designed to be compiled for a specific target. • An attempt to solve these problems, Gosling and others began work on a portable, platform-independent language that on a variety of CPUs under differing environments. • Second force was the introduction of World wide web demand a language that could useful in creating portable application. 2
Java “White Paper” Buzzwords • Simple • Object Oriented - technique for programming that focuses on the data (= objects) and on the interfaces to that object. • Portable • Architecture Neutral - By generating bytecode instructions, make it executable on many processors, given the presence of the Java runtime system. • Interpreted - Java interpreter can execute Java bytecodes directly on any machine. • Network-Savvy - Java has an extensive library of routines for coping with TCP/IP protocols like HTTP and FTP. • High Performance – JIT Compiler monitor the code and optimize the code for speed. • Robust - Emphasis on early checking for possible problems, later dynamic (runtime) checking, and eliminating situations that are error-prone. • Multithreaded • Secure - intended to be used in networked/distributed environments. • Dynamic 3
Java Milestones Year Milestones 1990 Sun decided to develop a software that could be used for consumer electronics. A project called Green Project created and head by James Gosling. 1991 Explored Possibility of using C++, with some updates announced a new language named “Oak” 1992 Demonstrate a new language to control a list of home appliances 1994 Team developed a new Web browser called “Hot Java” to locate and run applets. 1995 Oak was renamed to Java. Companies such as Netscape, Microsoft announced their support for Java 1996 Java became the language for Internet Programming and General purpose OO language. 4
Java Applications Java is used to develop two types of application program: • Stand-alone applications • Web applications (applets) 5
Java Environment JDK - Java Development Kit ( Program enable users to create java applications) JRE IDE - Java Runtime Environment ( Software to run java programs) - Eclipse, Jcreator, Net. Beans Setting Path My. Computer -> Environment Variables ->Advanced -> Path -> C: Jdk 1. 7bin 6
Sample Helloworld application /* Simple Helloworld Java application */ class test { public static void main(String[] args) { System. out. println(“Helloworld Java”); } } // save it as test. java Compile : javac test. java Execute : java test Helloworld Java 7
Process of Building and Running Java Applications 8
Sample Java Execution 9
Java is Compiled and Interpreted 10
How different from compiled languages? 11
Platform Independency 12
Introduction to JVM • JVM is the interpreter used to convert the byte code to machine code on the fly and execute it. • Byte code is optimized instruction set which independent of machine. JVM Architecture 13
JVM Advantages • Enable java program run in protected environment • Write once, run anywhere (one size fits all) • Browser can cache the downloaded code and reuse it later 14
Spot the errors 1. Fix the errors Class Demo public static void Main(String[] args) { System. out. println("afternoon"); system. out. println("morning"); } } If a No. Class. Def. Found. Error occurs when you run a program, what is the cause of the error? If a No. Such. Method. Error occurs when you run a program, what is the cause of the error? 15
Spot the errors 2. Identify and fix the errors in the following code: public class Welcome { public void main(string args[]) { System. out. println('Welcome to Java!); } ) 16
Input Processing import java. util public class Input. Demo { Scanner in; public static void main(String[] args) { in=new Scanner(System. in); System. out. println(“Enter a value”); int i=in. next. Int(); System. out. println(“User has Entered : ” + i ); } } next. Line, next. Double, has. Next. Int, has. Next. Double 17
Reading Input Using Console class – Java. io import java. util public class Input. Demo { public static void main(String[] args) { Console con= System. Console(); String name=con. read. Line(); String pass=con. read. Password(); System. out. println(“User Name : “+name +” and Password : ” + pass); } } 18
19
20
21
22
23
Declaration rules for a Java file Ø A source code file can have only one public class. Ø If the source file contains a public class, the filename must match the public class name. Ø A file can have only one package statement, but multiple imports. Ø The package statement (if any) must be the first (non-comment) line in a source file. Ø The import statements (if any) must come after the package and before the class declaration. Ø If there is no package statement, import statements must be the first (noncomment) statements in the source file. Ø package and import statements apply to all classes in the file. Ø A file can have more than one nonpublic class. Ø Files with no public classes have no naming restrictions. 24
Class Access modifiers § There are three access modifiers: public, protected, and private. § There are four access levels: public, protected, default, and private. § Classes can have only public or default access. § A class with default access can be seen only by classes within the same package. § A class with public access can be seen by all classes from all packages. § Class visibility revolves around whether code in one class can § Create an instance of another class § Extend (or subclass), another class § Access methods and variables of another class 25
Java Tokens Smallest individual units in a program are known as tokens. The compiler recognizes them for building up expressions and statements. A Java program is a collection of tokens, comments and white spaces. Java language includes five types of tokens. They are: 1. Identifiers 2. Comments 3. Keywords 3. Literals 4. Operators 5. Separators 26
Identifiers are programmer – designed tokens. They are used for naming classes, methods, variables, objects, labels, packages and interfaces in a program. Java identifiers follow the following rules: • Identifiers must start with a letter, a currency character ($), or a connecting character such as the underscore ( _ ). • Identifiers cannot start with a number! • After the first character, identifiers can contain any combination of letters, currency characters, connecting characters, or numbers. • In practice, there is no limit to the number of characters an identifier can contain. • You can't use a Java keyword as an identifier. • Identifiers in Java are case-sensitive; foo and FOO are two different identifiers. 27
Legal and Illegal identifiers Legal Identifiers Illegal identifiers 28
Naming Conventions • Names of all public methods and instance variables start with a leading lowercase letter. Example: average, sum • When more than one word are used in a name, the second and subsequent words are marked with a leading uppercase letters. Example: day. Temperature, first. Dayof. Month, total. Marks. • All private and local variables use only lowercase letters combined with underscores Example: length, batch_strength • All classes and interfaces start with a leading uppercase letter(and each subsequent word with a leading uppercase letter). Example: Student, Hello. Java, Vehicle, Motot. Cycle • Variables that represent constant values use all uppercase letters and underscores between words. Example: TOTAL, F_MAX, PRINCIPAL_AMOUNT 29
Comments help programmers to communicate and understand the program. They are not programming statements and thus are ignored by the compiler. In Java, comments are: Line Comment – Statement preceded by two slashes (//) Block Comment – Statement enclosed between /* and */ Java Document Comment – Statement enclosed between /** */ using Javadoc the document section converted to help files. 30
Java Keywords 31
Java Default Access Modifier Variable or method without access modifier is available to any class within the same package. Variables inside interface are implicitly public and final and methods in interface are public. 32
Eight Primitives: Eight primitives of java are: Four of them are integer types; two are floating-point number types; one is the character type char; and one is a Boolean type for truth values. 33
Data Types: Integer types : Float types : 34
Character Type In order to store character constants in memory. Java provides a character data type called char. The char type assumes a size of 2 bytes but, basically, it can hold only a single character. Boolean Type Boolean type is used when we want to test a particular condition during the execution of the program. There are only two values that a boolean type can take: true or false. Remember, both these words have been declared as keywords. Boolean type is denoted by the keyword boolean and uses only one bit of storage.
Variables is an identifier that denotes the storage location used to store a data value. Variable declaration denotes three things: • Type of the value the variable going to store. • Based on the place of declaration the initial value assigned. • Name of the variable to refer the value. • Based on the type the size of memory allocation is determined. Rules for variable declaration: Ø Variable name must contain numbers, alphabets, and underscore symbol. Ø They must not begin with a digit. Ø Uppercase and lowercase are distinct. This means that the variable Total is not the same as total or TOTAL. Ø It should not be a keyword. Ø White space is not allowed. Ø Variable names can be of any length. A variable must be declared before it can be assigned a value. A variable declared in a method must be assigned a value before it can be used. 36
Variable When a variable is assigned a value that is too large (in size) to be stored, it causes overflow. Java does not report warnings or errors on overflow. Example : int value = 2147483647 + 1; // value will actually be -2147483648 ( causes overflow) 37
Java variable types Three types of variable used in java: • Local variables ( declared inside function or construct) • Instance variable ( Non static variable declared inside the class and accessed using object) • Static variable (declared with static modifier and accessed using class name). Example: class Variable. Demo { int a=10; static int b=20; public static void main(String[] ar) { String c=“Hello”; Variable. Demo ob=new Variable. Demo(); System. out. println(c + b + ob. a); } } 38
Assignment Statements & Expression variable can get the value using assignment statement or assignment expression. Value is assigned using assignment operator Example : int a = 10; An expression represents a computation involving values, variables, and operators that, taking them together, evaluates to a value. Example: int x = 5 * (3 / 2) + 3 * 2; Note: Java is strongly typed language i. e. , variable on the left must be compatible with the data type of the value on the right. 39
Constants Named constants or constant represent permanent data that never changes its value, once gets initialized. Example: final double pi= 3. 14; Final indicate that you can assign to the variable once. 40
Operators in Java • • Arithmetic operators Relational operators Logical operators Assignment operators Increment and Decrement operators Conditional operators Bitwise logical operators Special operators 41
Arithmetic Operators Relational Operators Logical Operators 42
Bitwise Operator Example 43
Assignment Operator Assignment operators are used to assign the value of an expression to a variable. C# has a set of ‘shorthand’ assignment operators which are used in the form v op= exp v exp op Ex: - is the variable is the expression is the binary operator v op= exp is equivalent to v = v op(exp); x + = y + 1; is equivalent to x = x + (y +1) Advantages: . What appears on the left – hand side need not be repeated and therefore it becomes easier to write. . The statement is more concise and easier to read. . The use of shorthand operators results in a more efficient code. 44
Increment and Decrement Operator The operators are ++ and - ++ means Increment Operator - - means Decrement Operator The operator ++ adds 1 to the operand while – subtracts 1. Both are unary operators and are used in the following form: ++m; --m or or m++ m— ++m; is equivalent to m = m + 1 (or m + = 1; ) --m; is equivalent t o m = m – 1 (or m - = 1; ) We use the increment and decrement operators extensively in for and while loops For Example: Case 1 m = 5; y = ++m; Case 2 m = 5; y = m--; The statement a [ i ++ ] = 10; is equivalent to 45 a [ i ] = 10; i = i + 1;
Conditional Operator It is also known as Ternary operator Syntax: exp_1? exp_2: exp_3 Example Special Operators Instanceof Operator The instanceof is an object reference operator and returns true if the object on the left – hand side is an instance of the class given on the right – hand side. This operator allows us to determine whether the object belongs to a particular class or not. Example: person instanceof student Dot Operator objects. The dot operator (. ) is used to access the instance variables and methods of class Example: person 1. age //Reference to the variable age person 1. salary( ) //Reference to the method salary( ) 46
Decision Making Statements Two types of Decision making statements in java: • If else • Switch 47
If Statement ( one way if statement) Consists of a Boolean condition followed by one or statement. Syntax: if(Boolean_expression) { //Statements will execute if the Boolean expression is true } Example: Problem statement Calculate the area of the circle in case of radius is positive integer class Area { public static void main(String[] ar) { Scanner s=new Scanner(System. in); int rad=s. next. Int(); if(rad>0) { System. out. println( “ the area is “ + (3. 14 * rad)); } } } 48
Two way if statement When there are multiple conditions need to be evaluated then we can use if-else construct. If the condition is true one set of statement executes otherwise alternate set get executed. Syntax: if (boolean-expression) { statement(s)-for-the-true-case; } else { statement(s)-for-the-false-case; } 49
Nested if structure come into play when there are too many alternate conditions to be evaluated. Syntax: if (boolean-expression) { statement(s)-for-the-true-case; } } else { statement(s)-for-the-false-case; } 50
Nesting if…else statement if (Boolean-expression) { True-block statement(S) if (Boolean-expression) { True-block Statement(s) } else { False-block Statement(s) } } else { False-block statement(s) }
else if Ladder: if (condition_1) Statement_1; else if (condition_2) Statement_2; else if (condition_3) Statement_3; . . . Statement_n; else Default-Statement-x; else if (condition_n)
Common errors in Selection statement 1. Forgetting Necessary Braces 2. Wrong Semicolon at the if Line 53
Common errors in Selection statement 3. Redundant Testing of Boolean Values 4. Dangling else Ambiguity 54
Scenario to write if else: 1. 2. Code to check whether the number entered by user is even or odd number. Body Mass Index (BMI) is a measure of health on weight. It can be calculated by taking your weight in kilograms and dividing by the square of your height in meters. The interpretation of BMI for people 16 years or older is as follows: 3. Computing taxes : The United States federal personal income tax is calculated based on filing status and taxable income. There are four filing statuses: single filers, married filing jointly, married filing separately, and head of household. The tax rates vary every year. Table 3. 2 shows the rates for 2009. If you are, say, single with a taxable income of $10, 000, the first $8, 350 is taxed at 10% and the other $1, 650 is taxed at 15%. So, your tax is $1, 082. 5 55
Scenarios Lottery : Suppose you want to develop a program to play lottery. The program randomly generates a lottery of a two-digit number, prompts the user to enter a two-digit number, and determines whether the user wins according to the following rule: 1. If the user input matches the lottery in exact order, the award is $10, 000. 2. If all the digits in the user input match all the digits in the lottery, the award is $3, 000. 3. If one digit in the user input matches a digit in the lottery, the award is $1, 000. 56
Switch case A switch statement allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each case. If statement makes a problem difficult, when too many choices are there to evaluate in such circumstances switch is the alternative. Syntax: switch(expression) { case value : //Statements break; //optional default: //Optional //Statements } 57
THE SWITCH STATEMENT switch (expression) { case value_1: block_1; break; case value_2: block_2; break; case value_3: block_3; break; ---------------------default: default_block break; } Statement_x;
Rules for switch • The switch-expression must yield a value of char, byte, short, or int type and must always be enclosed in parentheses. • The value 1, and value. N must have the same data type as the value of the switch-expression. Note that value 1, and value. N are constant expressions, meaning that they cannot contain variables, such as 1 + x. • When the value in a case statement matches the value of the switch-expression, the statements starting from this case are executed until either a break statement or the end of the switch statement is reached. • The keyword break is optional. The break statement immediately ends the switch statement. • The default case, which is optional, can be used to perform actions when none of the specified cases matches the switch-expression. • The case statements are checked in sequential order, but the order of the cases (including the default case) does not matter. However, it is good programming style to follow the logical sequence of the cases and place the default case at the end. 59
Scenario Scissorrock-paper game: The program randomly generates a number 0, 1, or 2 representing scissor, rock, and paper. The program prompts the user to enter a number 0, 1, or 2 and displays a message indicating whether the user or the computer wins, loses, or draws. In a “main” method, generate a random integer between 1 and 13 to represent the possible values in a suit of playing cards. • Use a “switch” statement that applies cases to your random integer. • If the random number is 1, print out “Ace” to the console. • If the random number is 11, print out “Jack” to the console. • If the random number is 12, print out “Queen” to the console. • If the random number is 13, print out “King” to the console. The default case should simply print the random integer to the console. 60
Conditional Expression When we want to assign a value to a variable based on certain condition to be evaluated, the we can use conditional expression. Syntax: X= boolean-expression ? expression 1 : expression 2; Example : To find the biggest of two numbers: class Big { public static void main(String[] ar) { int a=Integer. parse. Int(ar[0]); int b=Integer. parse. Int(ar[1]); if(a>b) System. out. println ( “ a is big “); else System. out. println ( “ b is big “); } //replaced entire if statement int res = ( a > b ) ? a : b ; } Replaced by: 61
Exercises 1. Rewrite the following statement using a conditional expression: if (temperature > 90) pay = pay * 1. 5; else pay = pay * 1. 1; 2. Write a program that prompts the user to enter the month and year and displays the number of days in the month. For example, if the user entered month 2 and year 2000, the program should display that February 2000 has 29 days. If the user entered month 3 and year 2005, the program should display that March 2005 has 31 days. 3. Write a program that prompts the user to enter an integer and checks whether the number is divisible by both 5 and 6, or neither of them, or just one of them. Here are some sample runs for inputs 10, 30, and 23. 4. What is y after the following switch statement is executed? x = 3; y = 3; switch (x + 3) { case 6: y = 1; default: y += 1; } 62
5. Use a switch statement to rewrite the following if statement and draw the flow chart for the switch statement: if (a == 1) x += 5; else if (a == 2) x += 10; else if (a == 3) x += 16; else if (a == 4) x += 34; 6. Write a switch statement that assigns a String variable day. Name with Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, if day is 0, 1, 2, 3, 4, 5, 6, accordingly. 7. Rewrite the following if statement using the conditional operator: if (count % 10 == 0) System. out. print(count + "n"); else System. out. print(count + " "); 63
Loops • Loop is control structure that executes the sequence statement multiple times based on condition. Java supports three different set of iteration statements such as: § While loop § Do – While loop § For loop § foreach loop 64
While loop • Based on conditional expression inside the loop, the set of statements get executed multiple times Syntax: initialization; while(test_condition) { Body of the Loop } Example: Counting of numbers 1 to 100 //code int sum, count=0; while(count<100) { sum+=count; count++; } S. O. P(count); 65
Do-While loop do-while loop is a variation of the while loop. The do-while loop executes the loop body first, then checks the loop continuation-condition to determine whether to continue or terminate the loop. Syntax : do { // Loop body; Statement(s); } while (loop-continuation-condition); Tip: Use the do-while loop if you have statements inside the loop that must be executed at least once. import java. util. Scanner; public class Test. Do. While { public static void main(String[] args) { int data, sum = 0; Scanner input = new Scanner(System. in); System. out. print("Enter an int value (the program exits if the input is 0): "); data = input. next. Int(); sum += data; System. out. println("The sum is " + sum); }} 66
For Loop A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times. Syntax: for (initialization; test_condition; increment) { Body of the Loop } Example: public class Test { public static void main(String args[]) { for(int x =10; x <20; x = x+1) { System. out. print("value of x : "+ x ); System. out. print("n"); } } } 67
Enhanced for loop Syntax: for(declaration : expression) { //Statements } Declaration: The newly declared block variable, which is of a type compatible with the elements of the array you are accessing. The variable will be available within the for block and its value would be the same as the current array element. Expression: This evaluates to the array you need to loop through. The expression can be an array variable or method call that returns an array. Example: public class Test { public static void main(String args[]) { for( String s : args) { System. out. println(s); } } } 68
Scenario 1. Write a code to reverse the number using while loop. 2. Greatest Common divisor: Let the two input integers be n 1 and n 2. You know that number 1 is a common divisor, but it may not be the greatest common divisor. So, you can check whether k (fork 2, 3, 4, and so on) is a common divisor for n 1 and n 2, until k is greater than n 1 or n 2. Store the common divisor in a variable named gcd. Initially, gcd is 1. Whenever a new common divisor is found, it becomes the new gcd. 3. Predicating the Future Tuition: Suppose that the tuition for a university is $10, 000 this year and tuition increases 7% every year. In how many years will the tuition be doubled? 69
Review Questions Analyze the following code. Is count < 100 always true, always false, or sometimes true or sometimes false at Point A, Point B, and Point C? int count = 0; while (count < 100) { // Point A System. out. println("Welcome to Java!n"); count++; // Point B } // Point C How many times is the following loop body repeated? What is the printout of the loop? 70
What are the differences between a while loop and a do-while loop? Convert the following while loop into a do-while loop. int sum = 0; int number = input. next. Int(); while (number != 0) { sum += number; number = input. next. Int(); } Do the following two loops result in the same value in sum? Can you always convert a while loop into a for loop? Convert the following while loop into a for loop. int i = 1, sum = 0; while (sum < 10000) { sum = sum + i; i++; } 71
Suppose the input is 2 3 4 5 0. What is the output of the following code? import java. util. Scanner; public class Test { public static void main(String[] args) { Scanner input = new Scanner(System. in); int number, max; number = input. next. Int(); max = number; while (number != 0) { number = input. next. Int(); if (number > max) max = number; } System. out. println("max is " + max); System. out. println("number " + number); }} 72
What is the keyword break for? What is the keyword continue for? Will the following program terminate? If so, give the output. The for loop on the left is converted into the while loop on the right. What is wrong? Correct it. 73
After the break statement is executed in the following loop, which statement is executed? Show the output. for (int i = 1; i < 4; i++) { for (int j = 1; j < 4; j++) { if (i * j > 2) break; System. out. println(i * j); } System. out. println(i); } After the continue statement is executed in the following loop, which statement is executed? Show the output. for (int i = 1; i < 4; i++) { for (int j = 1; j < 4; j++) { if (i * j > 2) continue; System. out. println(i * j); } System. out. println(i); } 74
Identify and fix the errors in the following code: public class Test { public void main(String[] args) { for (int i = 0; i < 10; i++); sum += i; if (i < j); System. out. println(i) else System. out. println(j); while (j < 10); { j++; } while (j < 10) } } 75
What is wrong with the following code? • Write a program that displays all the numbers from 100 to 1000, ten per line, that are divisible by 5 and 6. • Use a while loop to find the smallest integer n such that n 2 is greater than 12, 000. • Write a program that reads an integer and displays all its smallest factors in increasing order. For example, if the input integer is 120, the output should be as follows: 2, 2, 2, 3, 5. 76
• Write a program that displays all the numbers from 100 to 1000, ten per line, that are divisible by 5 and 6. • Use a while loop to find the smallest integer n such that n 2 is greater than 12, 000. 77
Array • An array is a data structure which defines an ordered collection of a fixed number of homogeneous data elements • The size of an array is fixed and cannot increase to accommodate more elements • In Java, array are objects and can be of primitive data types or reference types • All elements in the array must be of the same data type Creating an Array 1. Declaring the array 2. Creating memory locations 3. Putting values into the memory locations. 1. Declaration of Arrays Syntax: type [ ] arrayname; Example: int [ ] counter; float [ ] marks; int [ ] x, y; 78
Introduction • An array is a group of like-typed variables that are referred to by a common name. • Arrays of any type can be created and may have one or more dimensions. • A specific element in an array is accessed by its index. • Arrays offer a convenient means of grouping related information. 79
2. Creating memory locations Syntax: arrayname = new type [size]; Examples: number = new int [5]; average = new float [10]; 3. Declaration and Creation in one step Syntax: type [ ] arrayname = new type [size]; Examples: int [ ] number = new int [5]; 4. Initialization of Arrays Syntax: type [ ] arrayname = {list of values}; Example: int [ ] number = {32, 45, 34, 56, 34}; int [ ] number = new int [3] {10, 20, 30}; 80
Alternative Array Declaration Syntax int al[] = new int[3]; int[] a 2 = new int[3]; The following declarations are also equivalent: • char twod 1[][] = new char[3][4]; • char[][] twod 2 = new char[3][4]; 81
Array Representation public class Test. Array { public static void main(String[] args) { double[] my. List = {1. 9, 2. 9, 3. 4, 1. 5}; // Print all the array elements for (double element: my. List) { System. out. println(element); }}} Output: 1. 9 2. 9 3. 4 3. 5 82
One-Dimensional Arrays • A one-dimensional array is a list of like-typed variables. • To create an array you first must create an array variable of the desired type. • The general form of a one- dimensional array declaration is • Syntax: type var-name[ ] Example 83
Multidimensional Arrays • In Java, multidimensional arrays are actually arrays of arrays. • To declare a multidimensional array variable, specify each additional index using another set of square brackets. example, • int two. D[][] = new int[4][5]; • Example 84
Variable – Size Arrays Variable – Size array is called Array of Array or Nested Array or Jagged Array Ex: int [ ] x = new int [3] [ ]; //Three rows array x [0] = new int [2] x [1] = new int [4] x [2] = new int [3] //First Rows has two elements //Second Rows has four elements //Third Rows has three elements x[0] [1] x[1] [3] x[2] [2] 85 85
public class My. Arrayc 2 { public static void main(String args[ ]) { Scanner s=new Scanner(System. in); int[][] jag=new int[3][]; jag[0]=new int[4]; jag[1]=new int[3]; jag[2]=new int[5]; System. out. println("Enter the array elements"); for(int i=0; i<jag. length; i++) { for(int j=0; j<jag[i]. length; j++) jag[i][j]=s. next. Int(); } for(int i=0; i<jag. length; i++) { for(int j=0; j<jag[i]. length; j++) { System. out. print(jag[i][j] + "t "); } System. out. println(); } } } 86
Variable length arguments Java allows us to pass a variable number of arguments of the same type to a method. The parameter in the method is declared as follows: type. Name. . . parameter. Names Rules: A function should contain only one variable length parameter The variable length parameter must be last in the list Preceded by any number usual parameters. 87
import java. util. *; class v. Argu { public static void print. Max(int. . . numbers ) { for (int i = 0; i < numbers. length; i++) { System. out. println( numbers[i] ); } } public static void main(String[] ar) { print. Max(1, 2, 3, 4, 5); } } 88
Example Problems • • • • How to sort an array and search an element inside it? How to sort an array and insert an element inside it? How to determine the upper bound of a two dimentional array? How to reverse an array? How to write an array of strings to the output console? How to search the minimum and the maximum element in an array? How to merge two arrays? How to fill (initialize at once) an array? How to extend an array after initialisation? How to sort an array and search an element inside it? How to remove an element of array? How to remove one array from another array? How to find common elements from arrays? How to find an object or a string in an Array? How to check if two arrays are equal or not? How to compare two arrays? 89
Quiz 1)What is the output of this program? class array_output { public static void main(String args[]) { int array_variable [] = new int[10]; for (int i = 0; i < 10; ++i) { array_variable[i] = i; System. out. print(array_variable[i] + " "); i++; } } } 2) class evaluate { public static void main(String args[]) { int arr[] = new int[] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; int n = 6; n = arr[n] / 2]; System. out. println(arr[n] / 2); } } 90
JAR File and Class Path 91
Introduction • The JAR file format is a compressed format used primarily to distribute Java applications and libraries. • It is built on the ZIP file format, and functions in a similar way • Many files are compressed and packaged together in a single file, making it easy to distribute the files over a network 92
Path & Class. Path • PATH and CLASSPATH are operating system level environment variables. • PATH is used to define where the system can find the executables (. exe) files – Example path= c: program filesjavajdk. 7. 0_05bin • CLASSPATH is used to specify the location of. class files 9
JAR Steps to create jar File: create a java code save the file compile the java files to create. class files create a manifest is the description contains the main class header Example: Main-Class: classname save it in. mft extension create jar java cfm name. jar manifest. mft *. class Executing the jar java –jar name. jar 9
- Slides: 94