Free Essay

Java Array

In:

Submitted By natrika
Words 1665
Pages 7
Java provides a data structure, the array, which stores a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type.
Instead of declaring individual variables, such as number0, number1, ..., and number99, you declare one array variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to represent individual variables.
This tutorial introduces how to declare array variables, create arrays, and process arrays using indexed variables.
Declaring Array Variables:
To use an array in a program, you must declare a variable to reference the array, and you must specify the type of array the variable can reference. Here is the syntax for declaring an array variable:
-------------------------------------------------
dataType[] arrayRefVar; // preferred way.
-------------------------------------------------

------------------------------------------------- or
-------------------------------------------------

------------------------------------------------- dataType arrayRefVar[]; // works but not preferred way.
Note: The style dataType[] arrayRefVar is preferred. The style dataType arrayRefVar[] comes from the C/C++ language and was adopted in Java to accommodate C/C++ programmers.
Example:
The following code snippets are examples of this syntax:
-------------------------------------------------
double[] myList; // preferred way.
-------------------------------------------------

------------------------------------------------- or
-------------------------------------------------

------------------------------------------------- double myList[]; // works but not preferred way.
Creating Arrays:
You can create an array by using the new operator with the following syntax:
-------------------------------------------------
arrayRefVar = new dataType[arraySize];
The above statement does two things: * It creates an array using new dataType[arraySize]; * It assigns the reference of the newly created array to the variable arrayRefVar.
Declaring an array variable, creating an array, and assigning the reference of the array to the variable can be combined in one statement, as shown below:
-------------------------------------------------
dataType[] arrayRefVar = new dataType[arraySize];
Alternatively you can create arrays as follows:
-------------------------------------------------
dataType[] arrayRefVar = {value0, value1, ..., valuek};
The array elements are accessed through the index. Array indices are 0-based; that is, they start from 0 to arrayRefVar.length-1.
Example:
Following statement declares an array variable, myList, creates an array of 10 elements of double type and assigns its reference to myList:
-------------------------------------------------
double[] myList = new double[10];
Following picture represents array myList. Here, myList holds ten double values and the indices are from 0 to 9.

Processing Arrays:
When processing array elements, we often use either for loop or foreach loop because all of the elements in an array are of the same type and the size of the array is known.
Example:
Here is a complete example of showing how to create, initialize and process arrays:
-------------------------------------------------
public class TestArray {
-------------------------------------------------

------------------------------------------------- public static void main(String[] args) {
-------------------------------------------------
double[] myList = {1.9, 2.9, 3.4, 3.5};
-------------------------------------------------

------------------------------------------------- // Print all the array elements
-------------------------------------------------
for (int i = 0; i < myList.length; i++) {
-------------------------------------------------
System.out.println(myList[i] + " ");
-------------------------------------------------
}
-------------------------------------------------
// Summing all elements
-------------------------------------------------
double total = 0;
-------------------------------------------------
for (int i = 0; i < myList.length; i++) {
-------------------------------------------------
total += myList[i];
-------------------------------------------------
}
-------------------------------------------------
System.out.println("Total is " + total);
-------------------------------------------------
// Finding the largest element
-------------------------------------------------
double max = myList[0];
-------------------------------------------------
for (int i = 1; i < myList.length; i++) {
-------------------------------------------------
if (myList[i] > max) max = myList[i];
-------------------------------------------------
}
-------------------------------------------------
System.out.println("Max is " + max);
-------------------------------------------------
}
-------------------------------------------------
}
This would produce the following result:
-------------------------------------------------
1.9
-------------------------------------------------
2.9
-------------------------------------------------
3.4
-------------------------------------------------
3.5
-------------------------------------------------
Total is 11.7
-------------------------------------------------
ax is 3.5
The foreach Loops:
JDK 1.5 introduced a new for loop known as foreach loop or enhanced for loop, which enables you to traverse the complete array sequentially without using an index variable.
Example:
The following code displays all the elements in the array myList:
-------------------------------------------------
public class TestArray {
-------------------------------------------------

------------------------------------------------- public static void main(String[] args) {
-------------------------------------------------
double[] myList = {1.9, 2.9, 3.4, 3.5};
-------------------------------------------------

------------------------------------------------- // Print all the array elements
-------------------------------------------------
for (double element: myList) {
-------------------------------------------------
System.out.println(element);
-------------------------------------------------
}
-------------------------------------------------
}
-------------------------------------------------
}
This would produce the following result:
-------------------------------------------------
1.9
-------------------------------------------------
2.9
-------------------------------------------------
3.4
-------------------------------------------------
3.5
Passing Arrays to Methods:
Just as you can pass primitive type values to methods, you can also pass arrays to methods. For example, the following method displays the elements in an int array:
-------------------------------------------------
public static void printArray(int[] array) {
-------------------------------------------------
for (int i = 0; i < array.length; i++) {
-------------------------------------------------
System.out.print(array[i] + " ");
-------------------------------------------------
}
-------------------------------------------------
}
You can invoke it by passing an array. For example, the following statement invokes the printArray method to display 3, 1, 2, 6, 4, and 2:
-------------------------------------------------
printArray(new int[]{3, 1, 2, 6, 4, 2});
Returning an Array from a Method:
A method may also return an array. For example, the method shown below returns an array that is the reversal of another array:
-------------------------------------------------
public static int[] reverse(int[] list) {
-------------------------------------------------
int[] result = new int[list.length];
-------------------------------------------------

------------------------------------------------- for (int i = 0, j = result.length - 1; i < list.length; i++, j--) {
-------------------------------------------------
result[j] = list[i];
-------------------------------------------------
}
-------------------------------------------------
return result;
-------------------------------------------------
}
The Arrays Class:
The java.util.Arrays class contains various static methods for sorting and searching arrays, comparing arrays, and filling array elements. These methods are overloaded for all primitive types. SN | Methods with Description | 1 | public static int binarySearch(Object[] a, Object key)Searches the specified array of Object ( Byte, Int , double, etc.) for the specified value using the binary search algorithm. The array must be sorted prior to making this call. This returns index of the search key, if it is contained in the list; otherwise, (-(insertion point + 1). | 2 | public static boolean equals(long[] a, long[] a2)Returns true if the two specified arrays of longs are equal to one another. Two arrays are considered equal if both arrays contain the same number of elements, and all corresponding pairs of elements in the two arrays are equal. This returns true if the two arrays are equal. Same method could be used by all other primitive data types (Byte, short, Int, etc.) | 3 | public static void fill(int[] a, int val)Assigns the specified int value to each element of the specified array of ints. Same method could be used by all other primitive data types (Byte, short, Int etc.) | 4 | public static void sort(Object[] a)Sorts the specified array of objects into ascending order, according to the natural ordering of its elements. Same method could be used by all other primitive data types ( Byte, short, Int, etc.) |

Creating a Two-Dimensional Array | |
The most basic multidimensional array is made of two dimensions. This is referred to as two-dimensional. To create a two-dimensional array, inside of one pair of square brackets, use two pairs (of square brackets). The formula you would use is: DataType[][] VariableName;
Although the pairs of brackets are empty, they will contain some numbers. There are various ways you can initialize a two-dimensional array. If you are declaring the array variable but are not ready to initialize it, use the following formula: DataType[][] VariableName = new DataType[Number1][Number2];
In Java, you can place the first square brackets on the right side of the name of the variable: DataType VariableName[][] = new DataType[Number1][Number2];
In the square brackets on the right side of the = operator, enter an integer in each. Here is an example: public class Exercise { public static void main(String[] args) throws Exception { String[][] members = new String[2][4]; } }
In our declaration, the members variable contains two lists. Each of the two lists contains 4 elements. This means that the first list contains 4 elements and the second list contains 4 elements. Therefore, the whole list is made of 8 elements (2 * 4 = 8). Because the variable is declared as aString, each of the 8 items must be a string.
You can also create a two-dimensional array that takes more than two lists, such as 3, 4, 5 or more. Here is an example: public class Exercise { public static void main(String[] args) throws Exception { String[][] members = new String[2][8]; } }
This time, the variable is a 2-dimensional (2 lists) array where each list contains 8 components. This means that the whole array contains 2 * 8 = 16 components.
If you want to declare the array variable using the first formula where you do not know the sizes of the lists, you must use the data type of the array and you can omit the right square brackets. Here is an example: public class Exercise { public static void main(String[] args) throws Exception { String members[][]; } } Initializing a Two-Dimensional Array | |
There are various ways you can initialize a multidimensional array. You can initialize an array variable when declaring it. To do this, on the right side of the declaration, do not include the values in the square brackets: public class Exercise { public static void main(String[] args) throws Exception { String[][] Members = new String[][] . . . ; } }
Before the closing semi-colon, type an opening and a closing curly brackets. Inside of the brackets, include a pair of an opening and a closing curly brackets for each internal array. Then, inside of a pair of curly brackets, provide a list of the values of the internal array, just as you would do for a one-dimensional array. Here is an example: public class Exercise { public static void main(String[] args) throws Exception { String[][] Members = new String[][] { { "Celeste", "Mathurin", "Alex", "Germain" }, // First List { "Jeremy", "Mathew", "Anselme", "Frederique" } // Second List }; } } Practical Learning: Creating a Two-Dimensional Array | | 1. To create and use a two-dimensional array, change the file as follows: package departmentstore5; public class Main { public static void main(String[] args) throws Exception { long itemID = 0; double price = 0.00d; String description = "Unknown"; // The first list contains women's items // The other contains non-women items long[][] itemNumbers = new long[][] { { 947783, 934687, 973947, 987598, 974937 }, { 739579, 367583, 743937, 437657, 467945 } }; String[][] itemNames = new String[][] { { "Women Double-faced wool coat", "Women Floral Silk Tank Blouse", "Women Push Up Bra", "Women Chiffon Blouse", "Women Bow Belt Skirtsuit" }, { "Men Cotton Polo Shirt", "Children Cable-knit Sweater ", "Children Bear Coverall Cotton", "Baby three-piece Set ", "Girls Jeans with Heart Belt " } }; double[][] unitPrices = new double[][] { { 275.25D, 180.05D, 50.00D, 265.35D, 245.55D }, { 45.55D, 25.65D, 28.25D, 48.55D, 19.95D } }; System.out.println("Item Identification"); System.out.println("Item Number: " + itemID); System.out.println("Description: " + description); System.out.printf("Unit Price: %.2f\n", price); } } |

Similar Documents

Free Essay

Jesus

...javax.microedition.lcdui Class TextField java.lang.Object | +--javax.microedition.lcdui.Item | +--javax.microedition.lcdui.TextField public class TextField extends Item A TextField is an editable text component that may be placed into a Form. It can be given a piece of text that is used as the initial value. A TextField has a maximum size, which is the maximum number of characters that can be stored in the object at any time (its capacity). This limit is enforced when the TextField instance is constructed, when the user is editing text within the TextField, as well as when the application program calls methods on the TextField that modify its contents. The maximum size is the maximum stored capacity and is unrelated to the number of characters that may be displayed at any given time. The number of characters displayed and their arrangement into rows and columns are determined by the device. The implementation may place a boundary on the maximum size, and the maximum size actually assigned may be smaller than the application had requested. The value actually assigned will be reflected in the value returned by getMaxSize(). A defensively-written application should compare this value to the maximum size requested and be prepared to handle cases where they differ. Input Constraints The TextField shares the concept of input constraints with the TextBox object. The different constraints allow the application to request that the user's input be restricted in a variety of ways...

Words: 3677 - Pages: 15

Free Essay

Join

...elements, or values, the array can hold. a.|the new operator| b.|the array’s size declarator| c.|the array’s data type| d.|the version of Java| ANS: B 2. What does the following statement do? double[] array1 = new double[10]; a.|Declares array1 to be a reference to an array of double values| b.|Creates an instance of an array of 10 double values| c.|Will allow valid subscripts in the range of 0 - 9| d.|All of the above| ANS: D 3. It is common practice to use a ____________ variable as a size declarator. a.|static| b.|reference| c.|final| d.|boolean| ANS: C 4. What do you call the number that is used as an index to pinpoint a specific element within an array? a.|subscript| b.|global unique identifier| c.|element| d.|argument| ANS: A 5. Subscript numbering always starts at what value? a.|0| b.|1| c.|-1| d.|None of the above| ANS: A 6. By default, Java initializes array elements with what value? a.|0| b.|100| c.|1| d.|-1| ANS: A 7. What will be the value of x[8] after the following code has been executed? final int SUB = 12; int[] x = new int[SUB]; int y = 100; for(int i = 0; i < SUB; i++) { x[i] = y; y += 10; } a.|170| b.|180| c.|190| d.|200| ANS: B 8. Java performs ____________, which means that it does not allow a statement to use a subscript that is outside the range of valid subscripts for the array. a.|active array sequencing| b.|array bounds checking| c.|scope...

Words: 1531 - Pages: 7

Premium Essay

Comp 230 Week 6 Lab Doc

...VBScript IP File Lab Objectives In this lab, students will complete the following objectives. * Create a VBScript program using NotePad++. * Write a two-dimensional array of IP addresses to a text file. * Read the IP Addresses text file into a script. * Append new Room/PC/IP address data to the text file. * Use the object Scripting.FileSystemObject. Lab Diagram During your session you will have access to the following lab configuration. Connecting to your lab For this lab, we will only need to connect to Vlab-PC1. * Vlab-PC1 To start simply click on the named Workstation from the device list (located on the left hand side of the screen) and click Power on in the tools bar. In some cases the devices may power on automatically. During the boot up process an activity indicator will be displayed in the name tab. * Black—Powered Off * Orange—Working on your request * Green—Ready to access If the remote console is not displayed automatically in the main window (or popup) click the Connect icon located in the tools bar to start your session. If the remote console does not appear please try the following option. * Switch between the HTML 5 and Java client versions in the tools bar. In the event this does not resolve your connectivity problems, please visit our Help/Support pages for additional resolution options. Task 1: Create the IP_FileWrite.vbs Program Note: All captures must be text only—DO NOT capture the NotePad++...

Words: 2335 - Pages: 10

Free Essay

Vba Intro

...questions about VBA. † Finance Dept, Kellogg School, Northwestern University, 2001 Sheridan Rd., Evanston, IL 60208, tel: 847-491-8344, fax: 847-491-5719, E-mail: r-mcdonald@northwestern.edu. CONTENTS 2 5 Storing and Retrieving Variables in a Worksheet 5.1 Using a named range to read and write numbers from spreadsheet . . . . . . . . . . . . . . . . . . . . . . . . . 5.2 Reading and Writing to Cells Which are not Named. . . 5.3 Using the “Cells” Function to Read and Write to Cells. 10 the . . . . . . . . . 11 12 13 6 Using Excel Functions 13 6.1 Using VBA to compute the Black-Scholes formula . . . . . . 13 6.2 The Object Browser . . . . . . . . . . . . . . . . . . . . . . . 15 7 Checking for Conditions 16 8 Arrays 17 8.1 Defining Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . 18 9 Iterating 19 9.1 A simple for loop . . . . . . . . . . . . . . . . . . . . . . . . . 20 9.2 Creating a binomial tree . . . . . . . . . . . . . . . . . . . . . 20 9.3 Other...

Words: 10883 - Pages: 44

Premium Essay

Logic and Design

...Programming Logic and Design, 6th Edition Chapter 6 Exercises 1. a. Design the logic for a program that allows a user to enter 10 numbers, then displays them in the reverse order of their entry. Answer: A sample solution follows Flowchart: Pseudocode: start Declarations num index num SIZE = 10 num numbers[SIZE] = 0,0,0,0,0,0,0,0,0,0 getReady() while index < SIZE getNumbers() endwhile finishUp() stop getReady() index = 0 return getNumbers() output “Enter a number for position ”, index input numbers[index] index = index + 1 return finishUp() output “The numbers in reverse order are: ” while index > 0 index = index – 1 output numbers[index] endwhile return b. Modify the reverse-display program so that the user can enter up to 10 numbers until a sentinel value is entered. Answer: A sample solution follows Flowchart: Pseudocode: start Declarations num index num SIZE = 10 num numbers[SIZE] = 0,0,0,0,0,0,0,0,0,0 string CONTINUE = “Y” string moreNumbers = CONTINUE getReady() while index < SIZE AND moreNumbers equal to CONTINUE getNumbers() endwhile finishUp() stop getReady() index = 0 output “Do you want to enter a number? (Y/N)” input moreNumbers return getNumbers() output “Enter a number for position ”, index input numbers[index] index = index...

Words: 4366 - Pages: 18

Free Essay

Ecet 370 Hw1

...======================================== DeVry College of New York ECET 370 HW #1: Dynamic 2D-array ------------------------------------------------- Objective: Write a program to calculate students’ average test scores and their grades. You may assume the following file input data: Johnson 85 83 77 91 76 Aniston 80 90 95 93 48 Cooper 78 81 11 90 73 Gupta 92 83 30 69 87 Blair 23 45 96 38 59 Clark 60 85 45 39 67 Kennedy 77 31 52 74 83 Bronson 93 94 89 77 97 Sunny 79 85 28 93 82 Smith 85 72 49 75 63 Use three arrays: a one-dimensional array to store the students’ names, a (parallel) two-dimensional array to store the test scores, and a parallel one dimensional array to store grades. Your program must contain at least the following functions: a function to read and store data into two arrays, a function to calculate the average test score and grade, and a function to output the results. Have your program also output the class average. Tools required: PC & Visual studio software Code: #include <iostream> #include <fstream> #include <sstream> #include <string> using namespace std; bool readStudentData(ifstream &inFile, string &name, int &score1, int &score2, int &score3, int &score4, int &score5) { string line; if (getline(inFile, line)) { string word; istringstream iss(line, istringstream::in); int count = 0; try { while (iss >> word) { //cout...

Words: 673 - Pages: 3

Free Essay

Matlab & Ss

...Lab 1: Introduction to MATLAB Warm-up MATLAB is a high-level programming language that has been used extensively to solve complex engineering problems. The language itself bears some similarities with ANSI C and FORTRAN. MATLAB works with three types of windows on your computer screen. These are the Command window, the Figure window and the Editor window. The Figure window only pops up whenever you plot something. The Editor window is used for writing and editing MATLAB programs (called M-files) and can be invoked in Windows from the pull-down menu after selecting File | New | M-file. In UNIX, the Editor window pops up when you type in the command window: edit filename (‘filename’ is the name of the file you want to create). The command window is the main window in which you communicate with the MATLAB interpreter. The MATLAB interpreter displays a command >> indicating that it is ready to accept commands from you. • View the MATLAB introduction by typing >> intro at the MATLAB prompt. This short introduction will demonstrate some basic MATLAB commands. • Explore MATLAB’s help capability by trying the following: >> help >> help plot >> help ops >> help arith • Type demo and explore some of the demos of MATLAB commands. • You can use the command window as a calculator, or you can use it to call other MATLAB programs (M-files). Say you want to evaluate the expression [pic], where a=1.2, b=2.3, c=4.5 and d=4....

Words: 2151 - Pages: 9

Free Essay

Cs205

...Assignment 2 1. Write a function that takes an array of int as a parameter and returns a count of odd numbers in the array.  Assume the array has MAX elements where MAX is a global constant int.  That means that before all of the functions there is a declaration like: const int MAX = 10; And arrays are declared like: int myArray[MAX]; Note: if you are having trouble with the array questions, be sure to work through the “Building Block” problems in this module first. 2. Write a function that takes an array of int as a parameter and returns the sum of odd numbers in the array.  Assume the array has MAX elements where MAX is a global constant int. 3. Rewrite your answer to the previous question as a recursive function. 4. Write a function that is passed two parameters: a one-dimensional array of int values, and an int value.   The function finds the value in the array that is closest in value to the second parameter.  For example, if the array had the values {5, -3, 18, 9, 4} and the second parameter was 11, then the function would return 9, because 9 is the closest value in the array to 11. If two values are equally distant, return either.  In the previous example, if the second parameter was 7, either 5 or 9 could be returned. Assume the array has MAX elements where MAX is a global constant int. 5. Write a function that initializes the components of a two-dimensional array in the following manner: components above the upper-left to lower-right diagonal should be set...

Words: 472 - Pages: 2

Free Essay

C Language

...Handout: Problem Solving and 'C' Programming Version: PSC/Handout/1107/1.0 Date: 16-11-07 Cognizant 500 Glen Pointe Center West Teaneck, NJ 07666 Ph: 201-801-0233 www.cognizant.com Problem Solving and C Programming TABLE OF CONTENTS About this Document ....................................................................................................................6 Target Audience ...........................................................................................................................6 Objectives .....................................................................................................................................6 Pre-requisite .................................................................................................................................6 Session 2: Introduction to Problem Solving and Programming Languages ...........................7 Learning Objectives ......................................................................................................................7 Problem Solving Aspect ...............................................................................................................7 Program Development Steps .......................................................................................................8 Introduction to Programming Languages ...................................................................................14 Types and Categories of Programming Languages...

Words: 4320 - Pages: 18

Free Essay

Array List

...ArrayList The differences between the Array and an ArrayList is a common question asked by beginners, just starting to code using Java. The Array and ArrayList are both used to store elements, which can be a primitive or an object in the case of ArrayList in Java. A main difference between the ArrayList and an Array in Java would be the static nature of the Array, but the ArrayList has a dynamic nature. Once an Array is created, programmers cannot change the size of it, but an ArrayList will be able to re-size itself at any time. There is one more notable difference between ArrayList and an Array (Paul, 2012). The Array is a core part of Java programming that has a special syntax and a semantics support within Java. An ArrayList is a part of the collection framework of popular classes, such as HashMap, Hashtable, and Vector. There are six more differences between Array and ArrayList which will be listed in numeral order: 1. First and Major difference between Array and ArrayList in Java would be that Array is a fixed length data structure, while ArrayList is a variable length collection class. 2. Another difference is that an Array cannot use Generics, due to it cannot store files, unlike the ArrayList that allows users to use Generics to ensure storage. 3. Programmers can compare the Array vs. ArrayList on how to calculate length of Array or size of an ArrayList. 4. One more major difference within an ArrayList and Array is that programmers cannot store primitives...

Words: 395 - Pages: 2

Premium Essay

Java

...Mohammad Doush Mr. Matthew Robert English 103 13 April 2013 Java the Programming Language Computer is very important in our live, we use computer in everywhere on our live. The doctor uses the computer to see file or pictures of his patients. Also, each engineer uses it in many ways of his work. The teacher in the classroom, employees in the offices and student in their study all of them use computer in them daily live. They are not using the mouse, the keyboard or the scream. They are using the applications by them these applications in the computer are like the soul in the body. The only way to build these applications is programming. To program we need to know one of the programming languages which are very similar each other. If you are professional in one of these languages you can be professional in the other language in a short period of time. It is acceptable if you have the same application written with Java once and with C++ or C sharp at the same time. So for this reason you cannot say that a programming language is better than others. There are three types of programming languages procedural, functional and object-oriented languages. The most uses of these languages are object-oriented and one of these languages is Java you can write any application you need using it. Also you can translate any application to its word. The message of the High-Level programming languages such as Algol and Pascal in first programming revolution was...

Words: 2352 - Pages: 10

Free Essay

Test Bank Data Structure and Java

...Test Bank for Data Structures with Java John R. Hubbard Anita Huray University of Richmond Chapter 1 Object-Oriented Programming Answer “True” or “False”: 1. An analysis of the profitability of a software solution would be done as part of the feasibility study for the project. 2. The best time to write a user manual for a software solution is during its maintenance stage. 3. The requirements analysis of a software project determines what individual components (classes) will be written. 4. In a large software project it is preferable to have the same engineers write the code as did the design. 5. In the context of software development, “implementation” refers to the actual writing of the code, using the design provided. 6. Software engineers use “OOP” as an acronym for “organized operational programming”. 7. The term “Javadoc” refers to the process of “doctoring” Java code so that it runs more efficiently. 8. Software engineers use “UML” as an acronym for “Unified Modeling Language”. 9. UML diagrams are used to represent classes and the relationships among them. 10. The “is-a” relationship between classes is called composition. 11. The “contains-a” relationship between classes is called aggregation. 12. The “has-a” relationship between classes is called inheritance. 1 Test Bank 2 13. A “mutable” class is one whose objects can be modified by the objects of other classes. 14...

Words: 1904 - Pages: 8

Premium Essay

Report

...Find Odd or Even 18 8. Convert Fahrenheit to Celsius 21 9. Display Date and Time 23 10.Largest of three integers 26 11. Java Programs part 1 28 12. Java Programs part 2 49 13. Java Programs part 3 74 14. Java Programs part 4 102 15. Java Programs part 5 120 16. Java Programs part 6 134 17. Java Interview Questions part 1 161 18. Java Interview Questions part 2 178 “Hello World” is passed as an argument to println method, you can print whatever you want. There is also a print method which doesn’t takes the cursor to beginning of next line as println does. System is a class, out is object of PrintStream class and println is the method. Output of program: Output of program: This code adds two matrix, you can modify it to add any number of matrices. You can create a Matrix class and create it’s objects and then create an add method which sum the objects, then you can add any number of matrices by repeatedly calling the method using a loop. Output of program: Other methods of searching are Linear search and Hashing. There is a binarySearch method in Arrays class which can also be used. binarySearch method returns the location if a match occurs otherwise - (x+1) where x is the no. of elements in the array, For example in the second case above when p is not present in characters array the returned value will be -6. This java program checks if a number is Armstrong or not. Armstrong number is a number which is equal to sum of digits raise to the...

Words: 1056 - Pages: 5

Premium Essay

Cd Key

...Java Quick Reference Console Input Scanner input = new Scanner(System.in); int intValue = input.nextInt(); long longValue = input.nextLong(); double doubleValue = input.nextDouble(); float floatValue = input.nextFloat(); String string = input.next(); Console Output System.out.println(anyValue); JOptionPane.showMessageDialog(null, "Enter input"); GUI Input Dialog String string = JOptionPane.showInputDialog( "Enter input"); int intValue = Integer.parseInt(string); double doubleValue = Double.parseDouble(string); Message Dialog Primitive Data Types byte short int long float double char boolean 8 bits 16 bits 32 bits 64 bits 32 bits 64 bits 16 bits true/false Arithmetic Operators + * / % ++var --var var++ var-addition subtraction multiplication division remainder preincrement predecrement postincrement postdecrement Assignment Operators = += -= *= /= %= assignment addition assignment subtraction assignment multiplication assignment division assignment remainder assignment Relational Operators < >= == != less than less than or equal to greater than greater than or equal to equal to not equal Logical Operators && || ! ^ short circuit AND short circuit OR NOT exclusive OR if Statements if (condition) { statements; } if (condition) { statements; } else { statements; } if (condition1) { statements; } else if (condition2) { statements; } else { statements; } switch Statements switch (intExpression) { case value1: statements; break; ... case valuen: statements; break;...

Words: 73366 - Pages: 294

Premium Essay

Java

...Software Design Introduction to the Java Programming Language Material drawn from [JDK99,Sun96,Mitchell99,Mancoridis00] Software Design (Java Tutorial) © SERG Java Features • “Write Once, Run Anywhere.” • Portability is possible because of Java virtual machine technology: – Interpreted – JIT Compilers • Similar to C++, but “cleaner”: – No pointers, typedef, preprocessor, structs, unions, multiple inheritance, goto, operator overloading, automatic coercions, free. Software Design (Java Tutorial) © SERG Java Subset for this Course • We will focus on a subset of the language that will allow us to develop a distributed application using CORBA. • Input and output will be character (terminal) based. • For detailed treatment of Java visit: – http://java.sun.com/docs/books/tutorial/index.html Software Design (Java Tutorial) © SERG Java Virtual Machine • Java programs run on a Java Virtual Machine. • Features: – – – – – Security Portability Superior dynamic resource management Resource location transparency Automatic garbage collection Software Design (Java Tutorial) © SERG The Java Environment Java Source File (*.java) Java Compiler (javac) Java Bytecode File (*.class) Java Virtual Machine (java) Software Design (Java Tutorial) © SERG Program Organization Source Files (.java) Running Application Running Applet JAVA BYTECODE COMPILER Class Files (.class) JAVA VIRTUAL MACHINE WEB BROWSER Software Design (Java Tutorial) © SERG Program Organization Standards •...

Words: 5230 - Pages: 21