An Overview of JAVA From basic to slightly less basic Jonathan-Lee Jones.

Slides:



Advertisements
Similar presentations
Classes and Objects. What is Design? The parts of the software including – what information each part holds – what things each part can do – how the various.
Advertisements

Arrays. What is an array An array is used to store a collection of data It is a collection of variables of the same type.
1 Lecture 11 Interfaces and Exception Handling from Chapters 9 and 10.
CS102--Object Oriented Programming Discussion 2: (programming strategy in java) – Two types of tasks – The use of arrays Copyright © 2008 Xiaoyan Li.
CS 106 Introduction to Computer Science I 02 / 18 / 2008 Instructor: Michael Eckmann.
Methods Liang, Chapter 4. What is a method? A method is a way of running an ‘encapsulated’ series of commands. System.out.println(“ Whazzup ”); JOptionPane.showMessageDialog(null,
Arrays Horstmann, Chapter 8. arrays Fintan Array of chars For example, a String variable contains an array of characters: An array is a data structure.
Classes, methods, and conditional statements We’re past the basics. These are the roots.
COMP 14 Introduction to Programming Mr. Joshua Stough February 28, 2005 Monday/Wednesday 11:00-12:15 Peabody Hall 218.
CS102--Object Oriented Programming Lecture 6: – The Arrays class – Multi-dimensional arrays Copyright © 2008 Xiaoyan Li.
Options for User Input Options for getting information from the user –Write event-driven code Con: requires a significant amount of new code to set-up.
EMB1006 JAVA Part 2 Arrays and onwards Jonathan-Lee Jones.
Week 4-5 Java Programming. Loops What is a loop? Loop is code that repeats itself a certain number of times There are two types of loops: For loop Used.
Fortran 1- Basics Chapters 1-2 in your Fortran book.
Methods (Functions) CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
Session One Introduction. Personal Introduction Role of programmers Robot Examination HUD & HID Uploading Code.
A Semantic Error in Google last weekend! Someone in Google typed an extra ‘/’ character into their URL List Link to CNN video report posted on Collab.
French Territory of St. Pierre CSE 114 – Computer Science I Arrays.
Lecture 2: Classes and Objects, using Scanner and String.
CSc2310 tutoring session, week 8 Fall, 2012 Haidong Xue 5:30pm—8:30pm 10/23/2012 and 10/24/2012 -Using Exceptions -Homework 4.
Basics of Java IMPORTANT: Read Chap 1-6 of How to think like a… Lecture 3.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Chapter 8: Collections: Arrays. 2 Objectives One-Dimensional Arrays Array Initialization The Arrays Class: Searching and Sorting Arrays as Arguments The.
Netprog: Java Intro1 Crash Course in Java. Netprog: Java Intro2 Why Java? Network Programming in Java is very different than in C/C++ –much more language.
Arrays Chapter 8. What if we need to store test scores for all students in our class. We could store each test score as a unique variable: int score1.
Arrays and Array Lists CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 6 l Array Basics l Arrays and Methods l Programming with Arrays.
Programming for Beginners Martin Nelson Elizabeth FitzGerald Lecture 5: Software Design & Testing; Revision Session.
1 Arrays An array is a collection of data values, all of which have the same type. The size of the array is fixed at creation. To refer to specific values.
Methods in Java. Program Modules in Java  Java programs are written by combining new methods and classes with predefined methods in the Java Application.
An Overview of JAVA From basic to slightly less basic Jonathan-Lee Jones.
Java Classes. Consider this simplistic class public class ProjInfo {ProjInfo() {System.out.println("This program computes factorial of number"); System.out.println("passed.
Chapter 8: Arrays and Functions Department of Computer Science Foundation Year Program Umm Alqura University, Makkah Computer Programming Skills
CMP-MX21: Lecture 4 Selections Steve Hordley. Overview 1. The if-else selection in JAVA 2. More useful JAVA operators 4. Other selection constructs in.
Primitive data Week 3. Lecture outcomes Primitive data – integer – double – string – char – Float – Long – boolean Declaration Initialisation Assignments.
Loops (cont.). Loop Statements  while statement  do statement  for statement while ( condition ) statement; do { statement list; } while ( condition.
© 2004 Pearson Addison-Wesley. All rights reserved ComS 207: Programming I Instructor: Alexander Stoytchev
Java Arrays and Methods MIS 3023 Business Programming Concepts II The University of Tulsa Professor: Akhilesh Bajaj All slides in this presentation ©Akhilesh.
BEGINNING PROGRAMMING.  Literally – giving instructions to a computer so that it does what you want  Practically – using a programming language (such.
Introduction to Methods. Previously discussed There are similarities in make up of that can help you remember the construct of a class a class in the.
Core Java Introduction Byju Veedu Ness Technologies httpdownload.oracle.com/javase/tutorial/getStarted/intro/definition.html.
Method Overloading  Methods of the same name can be declared in the same class for different sets of parameters  As the number, types and order of the.
CS101: Introduction to Computer Science Slides adapted from Sedgewick and Wayne Copyright © Your First Java.
Methods. Methods also known as functions or procedures. Methods are a way of capturing a sequence of computational steps into a reusable unit. Methods.
Title Slid CSC 444 Java Programming Arrays By Ralph B. Bisland, Jr.
User Defined Methods Methods are used to divide complicated programs into manageable pieces. There are predefined methods (methods that are already provided.
2.1 Functions. Functions in Mathematics f x y z f (x, y, z) Domain Range.
CSE 110 Review Session Hans Hovanitz, Kate Kincade, and Ian Nall.
Arrays. The array data structure Array is a collection of elements, that have the same data type Integers (int) Floating point numbers (float, double)
By Mr. Muhammad Pervez Akhtar
How do you do the following? Find the number of scores within 3 points of the average of 10 scores? What kind of a tool do you need? Today’s notes: Include.
Spring 2009 Programming Fundamentals I Java Programming XuanTung Hoang Lecture No. 8.
An Introduction to Java – Part 1 Erin Hamalainen CS 265 Sec 001 October 20, 2010.
Lecture 6: Methods MIT-AITI Kenya © 2005 MIT-Africa Internet Technology Initiative In this lecture, you will learn… What a method is Why we use.
CS 177 Recitation Week 1 – Intro to Java. Questions?
1 Simple Input Interactive Input - The Class Scanner n Command-Line Arguments.
1 Flow of Control Chapter 5. 2 Objectives You will be able to: Use the Java "if" statement to control flow of control within your program.  Use the Java.
Chapter 7 Continued Arrays & Strings. Arrays of Structures Arrays can contain structures as well as simple data types. Let’s look at an example of this,
Arrays and Array Lists CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
Chapter 9 Introduction to Arrays Fundamentals of Java.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
Data Structures & Algorithms CHAPTER 2 Arrays Ms. Manal Al-Asmari.
The need for Programming Languages
Lecture 2 D&D Chapter 2 & Intro to Eclipse IDE Date.
Single Dimensional Arrays
User input We’ve seen how to use the standard output buffer
User-Defined Functions
An Introduction to Java – Part I, language basics
Instructor: Alexander Stoytchev
Presentation transcript:

An Overview of JAVA From basic to slightly less basic Jonathan-Lee Jones

Overview Why JAVA? The VERY basics Data Types Arrays Functions & Methods and more advanced stuff Examples

Why JAVA? The programs that we are writing are very similar to their counterparts in several other languages, so our choice of language is not crucial. We use Java because it is widely available, embraces a full set of modern abstractions, and has a variety of automatic checks for mistakes in programs, so it is suitable for learning to program. There is no perfect language, and you certainly will be programming in other languages in the future.

The VERY Basics Programming in Java. We break the process of programming in Java into three steps: Create the program by typing it into a text editor and saving it to a file named, say, MyProgram.java. Compile it by typing "javac MyProgram.java" in the terminal window. Run (or execute) it by typing "java MyProgram" in the terminal window. The first step creates the program; the second translates it into a language more suitable for machine execution (and puts the result in a file named MyProgram.class); the third actually runs the program.

The VERY Basics public class HelloWorld { public static void main(String[] args) { System.out.println("Hello, World"); }

The VERY Basics class UseArgument { public static void main(String[] args) { System.out.print("Hello, "); System.out.print(args[0]); System.out.print(", "); System.out.print(args[1]); System.out.print(", "); System.out.print(args[2]); System.out.println("!"); }

The VERY Basics class UseArgument { public static void main(String[] args) { if(args.length>0){ System.out.print("Hello, "); System.out.print(args[0]); System.out.print(", "); System.out.print(args[1]); System.out.print(", "); System.out.print(args[2]); System.out.println("!"); System.out.println } Else System.out.println(“Error!”); }

Data Types There are many built in types in JAVA. These built in types can be primitive types, or object types. There are more options available as to what the programmer can do with the more complicated objects than the simple built in primitive types. intcharlong IntegerStringdouble floatDoubleboolean

Arrays Arrays can be though of as a set of values. They can be of any data type (and can even be of user made objects, or other arrays). You represent an array by using the square brackets [] after the data type, and is created using the new command and giving it a size. Eg. int[] numbers = new int[10]; An array is used when you want to store a series of values. The most common array you have all used already! Public static void main(String[] args) This line, in all of your programs contains the array args. It is an array of type String, and is used to store all the command line arguments input by the user.

Arrays When you create a new array using the “new” command, you initialise all the values in it to 0. An array is a series of memory locations, and the variable name points the first position. In JAVA, you can then index each position in the array by using Array[i] where I is the position you want to read. In C++ this is trickier, as you need to know the bit-size of each element to move through memory. If you use “System.out.println(ArrayName);” then you will print the pointer to the memory address the array starts at. Array[0] Array[1] Array[2] Array[3] Array[4] Array

Arrays This code will create an array of numbers between 0 and n, where n is specified by the user. In JAVA arrays start at 0, so the first value would be array[0]. public class createArray { public static void main(final String[] args) { final int n = Integer.parseInt(args[0]); int[]numbers = new int[n] for(int i=0; i<n; ++i) numbers[i] = I; }

Functions & Methods It is often easier to write functions to do a certain task. For example, if you know you are going to require a certain type of calculation repeatedly. Functions are usually of the type static, and methods dynamic, but apart from this they are very similar. public class Max2 { public static int max(final int a, final int b) { if (a>b) return a; else return b; } public static void main(final String[] args) { final int a = Integer.parseInt(args[0]); final int b = Integer.parseInt(args[1]); System.out.println("The maximum of " + a + " and " + b + " is " + max(a,b) + "."); }

Functions & Methods Functions can also be overloaded. This means that you can have a different function (in this case max) with the same name, but taking different inputs. JAVA identifies the correct one to use at compile time. public class Max4 { public static int max(final int a, final int b) { if (a>b) return a; else return b; } public static int max(final int a, final int b, final int c) { return max(max(a,b),c); } public static int max(final int a, final int b, final int c, final int d) { return max(max(a,b,c),d); } public static void main(final String[] args) { final int a = Integer.parseInt(args[0]); final int b = Integer.parseInt(args[1]); final int c = Integer.parseInt(args[2]); final int d = Integer.parseInt(args[3]); StdOut.printf("The maximum of %d, %d, %d, %d is %d.\n", a,b,c,d,max(a,b,c,d)); }

Functions & Methods The term methods usually refers to dynamically called functions. These are not determined at compile time, but are called implicitly on an object. For example this.minVal() would run the minVal method on this object. Methods are often used when the user creates objects of their own. A good example of this is a block object

Functions & Methods class Block{ private double height; private double width; private double length; public Block(double height, double width, double length) { this.height=height; this.width=width; this.length=length; } public double getTopArea() //legth x width { return length*width;} public double getFrontArea() //length x height {return length*height;} public double getSideArea() //width x height {return width*height;} public double getVolume() //area x height {return length*height*width;} }

Functions & Methods class BlockTest{ public static void main(String[] args){ if(args.length<3) { System.err.println(“Not enough arguments”); return; } else { double L = Double.parseDouble(args[0]); double W = Double.parseDouble(args[0]); double H = Double.parseDouble(args[0]); Block testB = new Block(L,W,H); System.out.println(“Volume = “ + testB.getVolume()); }

Thank You

EMB1006 JAVA Part 2 Arrays and onwards Jonathan-Lee Jones

Overview Array Recap Using an Array Example Finding the lowest and highest values in an array Defensive Programming

What is an Array As mentioned previously, an array is a method for storing multiple values that are linked together. The name of the array is a pointer to the first address in memory. An array can be of any type, primitive or object (even user defined object for example student records) and can even be made up of other arrays to give a 2 dimensional, 3 dimensional or even greater array.

An Example Array Arrays can be initialised as empty arrays, or just assigned values. To initialise as an empty array we use the following structure: – Int N = 100; – Int[] testArray = new int[N]; To Initialise by assigning values we use the following structure: – Int[] testArray = {1,2,3,4,5,6,7,8,9};

An Example Array class Deck { public static void main(final String args[]) { final String suit[] = {"Clubs", "Diamonds", "Hearts", "Spades" }; final String rank[] = {"2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King", "Ace" }; final int nr_suits = suit.length; final int nr_ranks = rank.length; final int nr_cards = nr_suits * nr_ranks; final String deck[] = new String[nr_cards]; for (int r = 0, base_index = 0; r < nr_ranks; ++r, base_index+=nr_suits) { for (int s=0; s < nr_suits; ++s) deck[base_index+s] = rank[r] + " of " + suit[s]; }

Shuffling the Deck Using an Array for (int i = 0; i < nr_cards; ++i) { final int rand = i + (int) (Math.random() * (nr_cards-i)); final String t = deck[rand]; deck[rand] = deck[i]; deck[i] = t; } The above code snippet will perform a shuffle on the deck. This is the best method to use with the tools you have for creating a mathematically fair shuffle. You can test this if you want! Below is how you print contents of array (remember printing out the name just prints the memory address pointer!) for (int i = 0; i < nr_cards; ++i) System.out.println(deck[i]);

Finding the Lowest and Highest Values Write a short piece of code to find both the highest and lowest numbers from an array of size N, and print these out, alongside their position in the array. You may need the following:- Integer.MIN_VALUE; Integer.MAX_VALUE; Array.length; For Loop Integer.parseInt();

Finding the Lowest and Highest Values class minmax{ public static void main(String[] args){ int N = args.length; int[]numbers = new int[N]; int min = Integer.MAX_VALUE; int max = Integer.MIN_VALUE; int maxPos =0; int minPos =0; for(int i=0;i<N;++i){ numbers[i]=Integer.parseInt(args[i]); if (numbers[i]>max){ max=numbers[i]; maxPos=i; } if (numbers[i]<min){ min=numbers[i]; minPos=i;}} System.out.println("Max = " + max + " at position " + maxPos +"."); System.out.println("Min = " + min + " at position " + minPos +"."); }} What would happen if zero arguments were entered? What else could go wrong?

Validating Input, Defensive programming When you allow the user to input values into the program, you inevitably invite errors at run time. If you ask for an int and they give a string for example. A large number of these can be avoided by using various scanner tools, but how would you validate command line input? You are tasked with writing a program to take in 3 numbers from the command line, then add the first 2 together then divide by the third. It is a trivial task, but you would be surprised how many problems may occur. Try to make sure that the program will not crash by throwing a run time exception, and also the program gives the expected values. What do you need to check to ensure this.

Validating Input, Defensive programming class threeNums{ public static void main(String[] args){ int a = Integer.parseInt(args[0]); int b = Integer.parseInt(args[1]); int c = Integer.parseInt(args[2]); double ans = (a+b)/c; System.out.println(“ans = ” + ans); }

Validating Input, Defensive programming lass threeNums{ public static void main(final String[] args){ final int a = Integer.parseInt(args[0]); final int b = Integer.parseInt(args[1]); final int c = Integer.parseInt(args[2]); double ans = (a+b)/c; System.out.println("ans = " + ans); }

Validating Input, Defensive programming Possible Errors that can occur:- 1.Not enough input arguments (program requires 3, what happens if it gets 2?) 2.If the third input is 0 what will happen? 3.What happens if a= 2,000,000,000 and b = 1,999,999,999? 4.What happens if the user inputs the following values by mistake:- 4 8u 22? Is there anything else that can go wrong with this code? What if the following numbers are input 1, 2 & 2? What output do you expect, and what do you get?