Introduction to Java & Fundamental Data Types

Similar documents
Full file at

12/22/11. Java How to Program, 9/e. Help you get started with Eclipse and NetBeans integrated development environments.

Programming with Java

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Course Outline. Introduction to java

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

Pace University. Fundamental Concepts of CS121 1

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal

Mobile Computing Professor Pushpendra Singh Indraprastha Institute of Information Technology Delhi Java Basics Lecture 02

Entry Point of Execution: the main Method. Elementary Programming. Learning Outcomes. Development Process

AP Computer Science A

Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. Java Basics

2.5 Another Application: Adding Integers

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Chapter 2: Basic Elements of C++

Introduction to Java Applications; Input/Output and Operators

Mr. Monroe s Guide to Mastering Java Syntax

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

Fundamental of Programming (C)

Object-Oriented Programming

CSc 10200! Introduction to Computing. Lecture 2-3 Edgardo Molina Fall 2013 City College of New York

Introduction to Programming Using Java (98-388)

UNIT- 3 Introduction to C++

Objectives. In this chapter, you will:

COSC 123 Computer Creativity. Introduction to Java. Dr. Ramon Lawrence University of British Columbia Okanagan

Università degli Studi di Bologna Facoltà di Ingegneria. Principles, Models, and Applications for Distributed Systems M

Programming for Engineers Introduction to C

Tester vs. Controller. Elementary Programming. Learning Outcomes. Compile Time vs. Run Time

Elementary Programming

Java-Array. This tutorial introduces how to declare array variables, create arrays, and process arrays using indexed variables.

Chapter 3. Selections

4 Programming Fundamentals. Introduction to Programming 1 1

COMP 202 Java in one week

Basics of Java Programming

Lecture Set 2: Starting Java

Getting started with Java

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal

Java+- Language Reference Manual

Repe$$on CSC 121 Fall 2015 Howard Rosenthal

Object oriented programming. Instructor: Masoud Asghari Web page: Ch: 3

Lecture Set 2: Starting Java

2.8. Decision Making: Equality and Relational Operators

Chapter 3: Operators, Expressions and Type Conversion

Expressions and Data Types CSC 121 Spring 2017 Howard Rosenthal

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups:

CSE 142 Su 04 Computer Programming 1 - Java. Objects

Introduction. C provides two styles of flow control:

Entry Point of Execution: the main Method. Elementary Programming. Compile Time vs. Run Time. Learning Outcomes

Contents. Jairo Pava COMS W4115 June 28, 2013 LEARN: Language Reference Manual

Array. Lecture 12. Based on Slides of Dr. Norazah Yusof

Lecture 05 I/O statements Printf, Scanf Simple statements, Compound statements

Lecture Notes. System.out.println( Circle radius: + radius + area: + area); radius radius area area value

Section 2.2 Your First Program in Java: Printing a Line of Text

Interpreted vs Compiled. Java Compile. Classes, Objects, and Methods. Hello World 10/6/2016. Python Interpreted. Java Compiled

Introduction to Java Applications

Repetition CSC 121 Fall 2014 Howard Rosenthal

Programming Language Basics

Full file at

Repe$$on CSC 121 Spring 2017 Howard Rosenthal

Lecture 3 Tao Wang 1

Chapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. Overview. Objectives. Teaching Tips. Quick Quizzes. Class Discussion Topics

Visual C# Instructor s Manual Table of Contents

13 th Windsor Regional Secondary School Computer Programming Competition

Java Programming. MSc Induction Tutorials Stefan Stafrace PhD Student Department of Computing

Control Statements: Part 1

cis20.1 design and implementation of software applications I fall 2007 lecture # I.2 topics: introduction to java, part 1

Chapter 2 Basic Elements of C++

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression

The C++ Language. Arizona State University 1

Data and Variables. Data Types Expressions. String Concatenation Variables Declaration Assignment Shorthand operators. Operators Precedence

COMP 202 Java in one week

Java Identifiers. Java Language Essentials. Java Keywords. Java Applications have Class. Slide Set 2: Java Essentials. Copyright 2012 R.M.

Program Fundamentals

CONTENTS: Compilation Data and Expressions COMP 202. More on Chapter 2

Flow Control. CSC215 Lecture

Values and Variables 1 / 30

boolean, char, class, const, double, else, final, float, for, if, import, int, long, new, public, return, static, throws, void, while

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines.

Computational Expression

ARG! Language Reference Manual

CS111: PROGRAMMING LANGUAGE II

What did we talk about last time? Examples switch statements

Slide 1 CS 170 Java Programming 1 The Switch Duration: 00:00:46 Advance mode: Auto

Building Java Programs Chapter 2

Università degli Studi di Bologna Facoltà di Ingegneria. Principles, Models, and Applications for Distributed Systems M

Introduction To Java. Chapter 1. Origins of the Java Language. Origins of the Java Language. Objects and Methods. Origins of the Java Language

CSCI 2010 Principles of Computer Science. Data and Expressions 08/09/2013 CSCI

Chapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. A Guide to this Instructor s Manual:

Oct Decision Structures cont d

First Java Program - Output to the Screen

5/3/2006. Today! HelloWorld in BlueJ. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont.

Fundamentals of Programming

CS 231 Data Structures and Algorithms, Fall 2016

Example: Monte Carlo Simulation 1

Important Java terminology

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.

Lecture 9. Assignment. Logical Operations. Logical Operations - Motivation 2/8/18

Chapter 2: Programming Concepts

Transcription:

Introduction to Java & Fundamental Data Types LECTURER: ATHENA TOUMBOURI

How to Create a New Java Project in Eclipse Eclipse is one of the most popular development environments for Java, as it contains everything you need to build a Java project from scratch. Before you can start working on your new project, you'll need to create it first. Creating a new Java project in Eclipse is fairly straightforward.

Declare your class and your main method. The main method public static void main(string[] args) is the method that will be executed when the programming is running. This main method will have the same method declaration in every Java program.

Write the line of code that will print out "Hello World." Wrong!!

Put it all together. Your final Hello World program should look like the following:

Run your program!!!!!

Let's look at the components of this line: System tells the system to do something. out tells the system that we are going to do some output stuff. println stands for "print line," so we are telling the system to print a line in the output. The parentheses around ("Hello World.") means that the method System.out.println() takes in a parameter, which, in this case, is the String "Hello World." Note that there are some rules in Java that we have to adhere to: You must always add a semicolon at the end of every line. Java is case sensitive, so you must write method names, variable names, and class names in the correct case or you will get an error. Blocks of code specific to a certain method or loop are encased between curly brackets.

Data Types Variables are nothing but reserved memory locations to store values. This means that when you create a variable you reserve some space in the memory. Based on the data type of a variable, the operating system allocates memory and decides what can be stored in the reserved memory. Therefore, by assigning different data types to variables, you can store integers, decimals, or characters in these variables. There are two data types available in Java: Primitive Data Types Reference/Object Data Types

Primitive data types: Primitive data types are those datatypes which are defined by java language itself. Reference data types: Reference data types are those data types which are provided as class by Java API or by class that you create. String is example of Reference data types provided by java.

Data Types Integer Double / Float Char Boolean String Primitive types Reference type

Integer Int data type is a 32-bit signed two's complement integer. Minimum value is - 2,147,483,648 (-2^31) Maximum value is 2,147,483,647(inclusive) (2^31-1) Integer is generally used as the default data type for integral values unless there is a concern about memory. The default value is 0 Example: int a = 100000, int b = -200000

String Is not a primitive type! It is an Object! The String class represents character strings. All string literals in Java programs, such as "ABC", are implemented as instances of this class. Strings are constant; their values cannot be changed after they are created. String buffers support mutable strings. Because String objects are immutable they can be shared. For example: String str = "ABC"; String str = ; That string is empty because there is nothing inside of the quotation marks, not even a space

Double / Float float Float data type is a single-precision 32-bit IEEE 754 floating point Float is mainly used to save memory in large arrays of floating point numbers Default value is 0.0f Float data type is never used for precise values such as currency Example: float f1 = 234.5f double double data type is a double-precision 64-bit IEEE 754 floating point This data type is generally used as the default data type for decimal values, generally the default choice Double data type should never be used for precise values such as currency Default value is 0.0d Example: double d1 = 123.4

double number = 4.67; in this example the name of the variable is called number (it can be called anything you want, by the way) and the type is double. We're setting this value to 4.67, although the number does not have to be written as a decimal. double number = 4; This is also valid, because 4 is the same as 4.0 in decimal.

Char Char data type is used to store any character Example: char lettera = 'A'

char Char c = g ; Before I continue, let me say that 'g' and 'G' are NOT THE SAME THING. These two characters are not equal because computers do not recognize them as the same symbol. More specifically, they have different ASCII values, but that's beyond what we're trying to learn in this lesson. Just remember that capital letters are not the same as lower case letters and vice versa.

Boolean Boolean data type represents one bit of information There are only two possible values: true and false This data type is used for simple flags that track true/false conditions Default value is false Example: Boolean one = true;

Boolean Boolean x = true; This is how a Boolean variable is created. In Java, the type of variable has to go before the variable's name. In this case the variable's name is x, and it's type is Boolean. We're also setting the variable equal to something, and here we're setting it to true. We could have easily just said: Boolean x;

Set Variables to a program There re some rules we have to follow when picking variable names. In general, you can name your variables whatever you want, as long as they follow these simple guidelines: Java variables cannot start with a number or special symbol. Java variables cannot be a keyword already.

Operators (+, *, /, -) Arithmetic operators are used in mathematical expressions in the same way that they are used in algebra.

Operator + (Addition) Adds values on either side of the operator. Example: A = 10 and B = 20 A + B will give 30

Operator - (Subtraction) Subtracts right-hand operand from left-hand operand. Example: A = 10 and B = 20 A - B will give -10

Operator * (Multiplication) Multiplies values on either side of the operator. Example: A = 10 and B = 20 A * B will give 200

Operator / (Division) Divides left-hand operand by right-hand operand. Example: A = 10 and B = 20 B / A will give 2

Also, assume integer variable A holds 10 and variable B holds 20, then

The Logical Operators The following table lists the logical operators Assume Boolean variables A holds true and variable B holds false, then:

The Relational Operators There are following relational operators supported by Java language. Assume variable A holds 10 and variable B holds 20, then:

Assignment Following are the assignment operators supported by Java language

Exercise: Write a program to print Hello World Write a program to print your name! Write a program to print the result 5*20

Output To output to the command line, we use either System.out.print () or System.out.println() or System.out.printf() Examples using println: System.out.println( One ); System.out.println( Two ); System.out.println( Buckle My Shoe );

Output Examples using print & println System.out.print( One ); System.out.print( Two ); System.out.print( Buckle my shoe ); System.out.println();

printf int number1, number2, sum; number1=10; number2=30; sum = number1 + number2; System.out.printf( The sum of %d + %d = %d, number1, number2, sum);

Change Line System.out.println -> change line System.out.print-> print in the same line

Command line Input The Scanner class is used for input from the command line. The Scanner class is in the package java.util so any program using the Scanner class must first include an import statement that is used to help the compiler locate the class. All import statements appear first in a java program before the class definition or any other statement (other than comments).

Import java.util.scanner; public class AddTwoNumbers{ public static void main(string[] str){ int x, y; //create a Scanner object to get input //System.in refers to standard input object Scanner input = new Scanner(System.in); //Prompt for and read the first integer //using the Scanner object s nextint method. //The program waits for the user to type in //an integer and press the ENTER key System.out.println( Enter the first integer: ); x = input.nextint(); System.out.println( Enter the next integer: ); y = input.nextint(); sum = x + y; System.out.println ( Sum is %d\n, sum); } //end of main } //end of class AddTwoNumbers

Exercise Write a program in Java which asked one number and then return the square of this number. For example: if I give the number 3 as input, the program will return the number 9.

-Conditional statements -Nested Decisions and switch statement

what is a conditional statement? Alternatively referred to as a conditional expression and conditional processing, a conditional statement is a set of rules performed if a certain condition is met. It is sometimes referred to as an If-Then statement, because IF a condition is met, THEN an action is performed

Conditional statements in physical language

Conditional operators The Equality and Relational Operators The equality and relational operators determine if one operand is greater than, less than, equal to, or not equal to another operand. The majority of these operators will probably look familiar to you as well. Keep in mind that you must use "==", not "=", when testing if two primitive values are equal. == equal to!= not equal to > greater than >= greater than or equal to < less than <= less than or equal to

AND OPERATOR- && Called Logical AND operator. If both the operands are non-zero, then the condition becomes true.

OR OPERATOR- Called Logical OR Operator. If any of the two operands are non-zero, then the condition becomes true.

NOT OPERATOR-! Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false.

Conditional statement in java A conditional statement in Java is one which checks for a condition and the course of program flow that it takes would depend on the outcome of the condition. If - else - is the most common conditional construct used in Java.

if statement: The if statement is the most basic of all the control flow statements. The if statement tells our program to execute a certain section of code only if a particular test evaluates to true.

Nested if statement: An if statement inside another the statement. If the outer if condition is true then the section of code under outer if condition would execute and it goes to the inner if condition. If inner if condition is true then the section of code under inner if condition would execute.

if-else statement: If a condition is true then the section of code under if would execute else the section of code under else would execute.

if-else-if statement:

Switch Case: The switch statement in Java is a multi branch statement. We use this in Java when we have multiple options to select. It executes particular option based on the value of an expression. Switch works with the byte, short, char, and int primitive data types. It also works with enumerated types, the String class, and a few special classes that wrap certain primitive types such as Character, Byte, Short, and Integer.

Example switch-case with break

Example switch-case without break

Create programs using if and if else statements Write a program in java which reads two numbers. If the first number is bigger than the second then the program will calculate and print the difference. Write a program in java which read the grade of a student and print: 8: GOOD 9: VERY GOOD 10: EXCELLENT o(solve the second exercise using if and after solve it using switch case)

While loop

What are the loops? In computer programming, a loop is a sequence of instruction s that is continually repeated until a certain condition is reached. Typically, a certain process is done, such as getting an item of data and changing it, and then some condition is checked such as whether a counter has reached a prescribed number.

Why use loops? Loops are used to repeat one statement or set statements more than one time. Most real programs contain some construct that loops within the program, performing repetitive actions on a stream of data or a region of memory.

While Loop In most computer programming languages, a while loop is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition. The while loop can be thought of as a repeating if statement.

Java while loop Java while loop is used to execute statement(s) until a condition is true. In this tutorial, we will learn to use while loop with examples. First of all, let's discuss while loop syntax: while (condition(s)) { // Body of loop } If the condition(s) holds true then the body of the loop is executed, after execution of the loop body condition is tested again and if the condition is still true then the body of the loop is executed again, and the process repeats until the condition(s) becomes false. The condition evaluates to true or false and if it is a constant, for example, while (c) { }, where c is a constant, then any non zero value of c is considered to be true, and zero is considered false.

You can test multiple conditions such as while (a > b && c!= 0) { // Loop body } Loop body is executed till value of variable a is greater than value of variable b and variable c isn't equal to zero. A body of a loop can contain more than one statement. For multiple statements, you need to place them in a block using {}, and if the body of a loop contains only one statement, you can optionally use {}. It is always recommended to use braces to make your program easy to read and understand.

Simple while-loop example

Java while loop break program We can write above program using a break statement. We test a user input and if it is zero then we use "break" to exit or come out of the loop.

Java while loop break continue program

Infinite while loop This loop would never end, its an infinite while loop. This is because condition is i >1 which would always be true as we are incrementing the value of i inside while loop

Example of infinite while loop

Create programs using while statement Write a program in java which reads numbers until the user give the number -1. Write a program in java that asked a user to give numbers and prints hello world until the user give odd number. Write a program in java that checks if the grade of test is between 1-100. you must to read 70 grades.

For Loop

What is for loop In computer science a for-loop (or simply for loop) is a programming language control statement for specifying iteration, which allows code to be executed repeatedly.

Java For Loop The Java for loop is used to iterate a part of the program several times. If the number of iteration is fixed, it is recommended to use for loop. There are three types of for loops in java. Simple For Loop For-each or Enhanced For Loop Labeled For Loop

Java Simple For Loop We can initialize the variable, check condition and increment/decrement value. It consists of four parts: Initialization: It is the initial condition which is executed once when the loop starts. Here, we can initialize the variable, or we can use an already initialized variable. It is an optional condition. Condition: It is the second condition which is executed each time to test the condition of the loop. It continues execution until the condition is false. It must return boolean value either true or false. It is an optional condition. Statement: The statement of the loop is executed each time until the second condition is false. Increment/Decrement: It increments or decrements the variable value. It is an optional condition.

Flowchart:

Java example //Java Program to demonstrate the example of for loop //which prints table of 1 public class ForExample { public static void main(string[] args) { //Code of Java for loop for(int i=1; i<=10; i++){ System.out.println(i); } } }

what is the output of previous example??

Java for-each Loop The for-each loop is used to traverse array or collection in java. It is easier to use than simple for loop because we don't need to increment value and use subscript notation. It works on elements basis not index. It returns element one by one in the defined variable.

what is the output of previous example??

Java Labeled For Loop We can have a name of each Java for loop. To do so, we use label before the for loop. It is useful if we have nested for loop so that we can break/continue specific for loop. Usually, break and continue keywords breaks/continues the innermost for loop only.

what is the output of previous example??

Java Infinitive For Loop If you use two semicolons ;; in the for loop, it will be infinitive for loop.

Infinite for loop

Do while loop

do while loop In most computer programming languages, a do while loop is a control flow statement that executes a block of code at least once, and then repeatedly executes the block, or not, depending on a given boolean condition at the end of the block.

A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to execute at least one time. Notice that the Boolean expression appears at the end of the loop, so the statements in the loop execute once before the Boolean is tested. If the Boolean expression is true, the control jumps back up to do statement, and the statements in the loop execute again. This process repeats until the Boolean expression is false Following is the syntax of a do...while loop

Example do while

What is the output?

Java Infinitive do-while Loop

Nested Loops and Good Programming Style

Nested Loops java The placing of one loop inside the body of another loop is called nesting. When you "nest" two loops, the outer loop takes control of the number of complete repetitions of the inner loop. While all types of loops may be nested, the most commonly nested loops are for loops.

When working with nested loops, the outer loop changes only after the inner loop is completely finished

Example 1: The far-right number, however, is not the only number that is moving. All of the other numbers are moving also, but at a much slower pace. For every 10 numbers that move in the column on the right, the adjacent column is incremented by one. The two nested loops shown below may be used to imitate the movement of the two far-right numbers of a web counter or an odometer:

Example 2: Program to create a pattern

Example 3: Java Nested for Loop

Common Errors

Example: nested loop: A loop placed inside another loop. for (int i = 1; i <= 5; i++) { for (int j = 1; j <= 10; j++) { System.out.print("*"); } System.out.println(); // to end the line } Output: ********** ********** ********** ********** ********** The outer loop repeats 5 times; the inner one 10 times. "sets and reps" exercise analogy

Exercise 1: What is the output of the following nested for loops? for (int i = 1; i <= 5; i++) { for (int j = 1; j <= i; j++) { System.out.print("*"); } System.out.println(); }

Exercise 2: What is the output of the following nested for loops? for (int i = 1; i <= 5; i++) { for (int j = 1; j <= i; j++) { System.out.print(i); } System.out.println(); }

Guidelines for good programming 1 Formatting 1.1 - Indentation All indents are four spaces. All indenting is done with spaces, not tabs. Matching braces always line up vertically in the same column as their construct. All if, while and for statements must use braces even if they control just one statement.

1.2 - Spacing All method names should be immediately followed by a left parenthesis. All array dereferences should be immediately followed by a left square bracket. Binary operators should have a space on either side. Unary operators should be immediately preceded or followed by their operand. Commas and semicolons are always followed by whitespace. All casts should be written with no spaces. The keywords if, while, for, switch, and catch must be followed by a space.

1.3 - Class Member Ordering class Order { // fields // constructors // methods } 1.4 - Maximum Line Length Avoid making lines longer than 120 characters. 1.5 Parentheses Parentheses should be used in expressions not only to specify order of precedence, but also to help simplify the expression. When in doubt, parenthesize

2 - Identifiers All identifiers use letters ('A' through 'Z' and 'a' through 'z') and numbers ('0' through '9') only. No underscores, dollar signs or non-ascii characters. 2.1 - Classes and Interfaces All class and interface identifiers will use mixed case. The first letter of each word in the name will be uppercase, including the first letter of the name. All other letters will be in lowercase, except in the case of an acronym, which will be all upper case. 2.2 - Packages Package names will use lower case characters only. Try to keep the length under eight (8) characters. Multi-word package names should be avoided. 2.3 - All Other Identifiers All other identifiers, including (but not limited to) fields, local variables, methods and parameters, will use the following naming convention. This includes identifiers for constants. The first letter of each word in the name will be uppercase, except for the first letter of the name. All other letters will be in lowercase, except in the case of an embedded acronym, which will be all uppercase. Leading acronyms are all lower case. Hungarian notation and scope identification are not allowed. Test code is permitted to use underscores in identifiers for methods and fields

3 - Coding 3.1 - Constructs to Avoid Never use do..while Never use return in the middle of a method Never use continue. Never use break other than in a switch statement. 3.2 - Do Not Compound Increment Or Decrement Operators Use a separate line for an increment or decrement. Never use pre-increment or predecrement 3.3 - Initialization Declare variables as close as possible to where they are used 3.4 - Access All fields must be private, except for some constants.

Use of Comments In programming, comments are portion of the program intended for you and your fellow programmers to understand the code. They are completely ignored by Java compilers. In Java programming language, there are two types of comments:

Traditional comment /*... */ This is a multiline comment that can span over multiple lines. The Java compiler ignores everything from /*... */. For example:

End of Line Comment // The compiler ignores everything from // to the end of the line. For example:

Use Comments the Right Way Comments shouldn't be the substitute for a way to explain poorly written code in English. Write well structured and readable code, and then use comments. In most cases, use comments to explain 'why' rather than 'how' and you are good to go.

Parts of Java Program Java programs are made up of different parts. We ll begin by looking at a simple example: Comments Class Definition Main Method

The Class Definition FirstProgram is the name of the Java class. Note that the file must be named to class name with.java extension. It means that this program must be saved as FirstProgram.java The second line of the program consists of the left brace, which is matched with the second right brace (the very last brace). These braces together mark the beginning and end of (the body of) the class FirstProgram. Later we ll discuss class in details, for now it is enough to know that every application begins with a class definition.

The main Method In Java, every application must contain a main method whose signature is: The JVM starts running any program by executing this method first. Finally, the line: prints the characters between quotes to the console.

Arrays

What are the arrays? An array is a series of data elements that, in most programming languages, is stored in consecutive memory locations. The datum held in an array is called an element, and each element occupies a position in the array known as an index. 0 1 2 N-1

Why use Arrays in a program? Array reduce the number of variable names in the program Sales[K] versus Sales1, Sales2, SalesN,. Arrays increase the flexibility of the program. Arrays reduce the number of If-Then statements needed in selection processing. if Sales[K] Then rather than Sales1 Then Sales2 Then Sales3 Then Arrays improve efficiency by allowing data to be read into the program once but processed as many time as necessary.

Arrays in Java: An array is a group of like-typed variables that are referred to by a common name. Following are some important point about Java arrays: I. In Java all arrays are dynamically allocated.(discussed below) II. III. Since arrays are objects in Java, we can find their length using member length. A Java array variable can also be declared like other variables with [] after the data type. IV. The variables in the array are ordered and each have an index beginning from 0. V. Java array can be also be used as a static field, a local variable or a method parameter. VI. The size of an array must be specified by an int value and not long or short.

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. The general form of a one-dimensional array declaration is: type var-name[]; or Example type[] var-name; //preferred way The following code snippets are examples of this syntax

Creating Arrays You can create an array by using the new operator with the following syntax: The above statement does two things: 1. It creates an array using new datatype[arraysize]. 2. 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: Alternatively you can create arrays as follows : 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: 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 because all of the elements in an array are of the same type and the size of the array is known. Print all the array elements: public class TestArray { public static void main(string[] args) { } } double[] mylist = {1.9, 2.9, 3.4, 3.5}; for (int i = 0; i < mylist.length; i++) { System.out.println(myList[i] + " "); }

Summing all elements public class TestArray { public static void main(string[] args) { double[] mylist = {1.9, 2.9, 3.4, 3.5}; double total = 0; for (int i = 0; i < mylist.length; i++) { total += mylist[i]; } } } System.out.println("Total is " + total);

Finding the largest element public class TestArray { public static void main(string[] args) { double[] mylist = {1.9, 2.9, 3.4, 3.5}; 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); } }

The foreach Loops Enables you to traverse the complete array sequentially without using an index variable. Example:

The previous program will produce the following result: 1.9 2.9 3.4 3.5 Prints all the elements in the Array!!!

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. Example:

Returning an Array from a Method A method may also return an array. For example, the following method returns an array that is the reversal of another array:

Exercises: Write a Java program to calculate the average value of array elements. (Average = sum / count) Write a Java program to test if an integer array contains the number 5. Write a Java program to find the maximum and minimum value of an array.

Parallel arrays and multidimensional arrays

Parallel arrays In computing, a group of parallel arrays (also known as structure of arrays or SoA) is a form of implicit data structure that uses multiple arrays to represent a singular array of records. Simply, Parallel arrays are several arrays with the same number of elements that work in tandem to organize data.

Why we use them? It keeps a separate, homogeneous data array for each field of the record, each having the same number of elements. The advantage of parallel arrays in Java is as an measure to reduce object allocation. For a large enough collection of objects, 3 arrays will occupy less space AND use fewer objects than a single array of instances of some custom class.

Example: The first array is the dog's name, the second array is the dog's score in round 1 of the competition, and the third array is the dog's score in round 2 of the competition. The arrays are parallel, in that the dog in the first element of the first array has the scores represented in the first elements of the second and third arrays

//Printing the dog competition information: for(int i = 0; i < dogname.length; i++) { System.out.println(dogname[i]); System.out.println(round1[i]); System.out.println(round2[i]); }

Program with parallel arrays

..Output?

Exercise: You have the following Arrays:

Representing the properties of many different students To represent the student ID of a number of students, we can use an array of int To represent the name of a number of students, we can use an separate array of String To represent the major of a number of students, we can use an separate array of String To represent the level of a number of students, we can use an separate array of int

information on 3 students

How can I print the major of John Doe, if I don t know that the John Doe is first in the Array?

Multidimensional arrays A multidimensional array in Java is really an array within an array (and as more dimensions are added, the hall of mirrors continues).

So, It's also possible to create an array of arrays known as multidimensional array. For example:

***Remember, Java uses zero-based indexing, that is, indexing of arrays in Java starts with 0 and not 1.

TWO FOR LOOP Example: Print all elements of 2d array Using Loop

EXERCISES: 1) Write a Java program to find and print all EVEN numbers in 2d Array 5x6.