Algorithm Programming 1 89-210 Bar-Ilan University 2007-2008 תשס"ח by Moshe Fresko.

Slides:



Advertisements
Similar presentations
Types, Variables and Operators Computer Engineering Department Java Course Asst. Prof. Dr. Ahmet Sayar Kocaeli University - Fall 2013.
Advertisements

CERTIFICATION OBJECTIVES Use Class Members Develop Wrapper Code & Autoboxing Code Determine the Effects of Passing Variables into Methods Recognize when.
IntroductionIntroduction  Computer program: an ordered sequence of statements whose objective is to accomplish a task.  Programming: process of planning.
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
Intermediate Java Sakir YUCEL MISM/MSIT Carnegie Mellon University Program Control Slides adapted from Steven Roehrig.
Java Syntax Primitive data types Operators Control statements.
Program Elements We can now examine the core elements of programming (as implemented in Java) We focuse on: data types variable declaration and use, constants.
Primitive Types Java supports two kinds of types of values – objects, and – values of primitive data types variables store – either references to objects.
CSci 142 Data and Expressions. 2  Topics  Strings  Primitive data types  Using variables and constants  Expressions and operator precedence  Data.
JAVA PROGRAMMING PART II.
Chapter 2: Introducing Data Types and Operators.  Know Java’s primitive types  Use literals  Initialize variables  Know the scope rules of variables.
© 2001 by Ashby M. Woolf Revision 3 Using Java Operators The Basic Toolkit Pliers, Screwdriver, Hammer and Drill.
Chapter 4: Initialization and cleanup ● How to initializa an object ● Method overloading ● Cleanup: Finalization and gaurbage collection.
General Features of Java Programming Language Variables and Data Types Operators Expressions Control Flow Statements.
System development with Java Lecture 2. Rina Errors A program can have three types of errors: Syntax and semantic errors – called.
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
Operators Using Java operators An operator takes one or more arguments and produces a new value. All operators produce a value from their.
Algorithm Programming Bar-Ilan University תשס"ח by Moshe Fresko.
Outline Character Strings Variables and Assignment Primitive Data Types Expressions Data Conversion Interactive Programs Graphics Applets Drawing Shapes.
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.
Java Structure import java_packages; class JavaClass { member variables declarations; void otherMethod( ) { } public static void main(String[]
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.
S ystem P rogrammers' A ssociation for R esearching C omputer S ystems 3. Operators SPARCS JAVA Study.
 The if statement and the switch statement are types of conditional/decision controls that allow your program.  Java also provides three different looping.
COMPUTER PROGRAMMING. variable What is variable? a portion of memory to store a determined value. Each variable needs an identifier that distinguishes.
4.1 Object Operations operators Dot (. ) and new operate on objects The assignment operator ( = ) Arithmetic operators + - * / % Unary operators.
Controlling Program Flow. Data Types and Variable Declarations Controlling Program Flow.
15-Nov-15 All the Operators. operators.ppt 2 Precedence An operator with higher precedence is done earlier (precedes) one with lower precedence A higher.
Apr, 2011 Dating with Java Larry Li. Objective Hello world program Setup development environment Data types and variables Operators and Expressions Control.
3: Controlling Program Flow Using Java operators Mathematical operators Relational operators Logical operators –Primitive type: ALL (the same with C) –String:
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.
Java Language Basics By Keywords Keywords of Java are given below – abstract continue for new switch assert *** default goto * package.
Operators in JAVA. Operator An operator is a symbol that operates on one or more arguments to produce a result. Java provides a rich set of operators.
Java Nuts and Bolts Variables and Data Types Operators Expressions Control Flow Statements Arrays and Strings.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
CSM-Java Programming-I Spring,2005 Fundamental Data Types Lesson - 2.
Aside: Running Supplied *.java Programs Just double clicking on a *.java file may not be too useful! 1.In Eclipse, create a project for this program or.
2: Basics Basics Programming C# © 2003 DevelopMentor, Inc. 12/1/2003.
An Introduction to Java – Part 1 Erin Hamalainen CS 265 Sec 001 October 20, 2010.
Chapter 1 Java Programming Review. Introduction Java is platform-independent, meaning that you can write a program once and run it anywhere. Java programs.
0 Chap.2. Types, Operators, and Expressions 2.1Variable Names 2.2Data Types and Sizes 2.3Constants 2.4Declarations 2.5Arithmetic Operators 2.6Relational.
Java Basics. Tokens: 1.Keywords int test12 = 10, i; int TEst12 = 20; Int keyword is used to declare integer variables All Key words are lower case java.
JAVA Programming (Session 2) “When you are willing to make sacrifices for a great cause, you will never be alone.” Instructor: รัฐภูมิ เถื่อนถนอม
 Array ◦ Single & Multi-dimensional  Java Operators ◦ Assignment ◦ Arithmetic ◦ Relational ◦ Logical ◦ Bitwise & other.
1 Lecture # 2. * Introducing Programming with an Example * Identifiers, Variables, and Constants * Primitive Data Types * Byte, short, int, long, float,
Object-Oriented Programming and Problem Solving Dr. Ramzi Saifan Introduction and basics of Java Slides adapted from Steven Roehrig.
Object Oriented Programming Lecture 2: BallWorld.
CSE 110: Programming Language I Matin Saad Abdullah UB 1222.
Today… Continue Building Expressions: –Literals –Constants –Casting –Array Declaration –Operators and Operator Precedence –Keywords Winter 2016CMPE212.
 It is a pure oops language and a high level language.  It was developed at sun microsystems by James Gosling.
Programming in Java Sachin Malhotra, Chairperson, PGDM-IT, IMS Ghaziabad Saurabh Chaudhary, Dean, Academics, IMS Ghaziabad.
2.0 FUNDAMENTALS OF JAVA PROGRAMMING LANGUAGE
Selections Java.
Sachin Malhotra Saurabh Choudhary
Java Primer 1: Types, Classes and Operators
Multiple variables can be created in one declaration
C Basics.
Starting JavaProgramming
Character Set The character set of C represents alphabet, digit or any symbol used to represent information. Types Character Set Uppercase Alphabets A,
All the Operators 22-Nov-18.
An Introduction to Java – Part I, language basics
All the Operators 4-Dec-18.
Java Tokens & Data types
Chapter 2: Java Fundamentals
Expressions and Assignment
Winter 2019 CMPE212 4/7/2019 CMPE212 – Reminders
OOP With Java/ course1 Sundus Abid-Almuttalib
Chap 2. Identifiers, Keywords, and Types
ENERGY 211 / CME 211 Lecture 5 October 1, 2008.
Review of Java Fundamentals
Presentation transcript:

Algorithm Programming Bar-Ilan University תשס"ח by Moshe Fresko

Java Language Specifications

Controlling Program Flow  Operators Addition(+), subtraction and unary minus(-), multiplication(*), division(/), assignment(=) etc. Produces a Value Side Effect Operators work only with primitives, except =,==,!= for objects and +,+= for String  Operator Precedence  Assignment =

Primitive Data Types Type Size Min Max Wrapper Defaut boolean Boolean false char 16-bit Uni 0 Uni Character ‘\u0000’ byte 8-bit Byte (byte)0 short 16-bit Short (short)0 int 32-bit Integer 0 long 64-bit Long 0L float 32-bit Float 0.0f double 64-bit Double 0.0d void - Void

Assignment Operator (=)  lvalue=rvalue  rvalue is constant, variable, or expression  lvalue is a physical space to store the value  Primitive assignment  Object assignment class Number { int i; } public class Assignment { public static void main(String[] args) { Number n1 = new Number(); Number n2 = new Number(); n1.i = 9; n2.i = 47; System.out.println("1: n1.i: " + n1.i + ", n2.i: " + n2.i); n1 = n2; System.out.println("2: n1.i: " + n1.i + ", n2.i: " + n2.i); n1.i = 27; System.out.println("3: n1.i: " + n1.i + ", n2.i: " + n2.i); }

Function Calls  Aliasing can occur in Function Call class Letter { char c; } public class PassObject { static void f(Letter y) { y.c = 'z'; } public static void main(String[] args) { Letter x = new Letter(); x.c = 'a'; System.out.println("1: x.c: " + x.c); f(x); System.out.println("2: x.c: " + x.c); }  Primitive types pass as copy by value  Values are returned as return-by-value

Mathematical Operators int i, j, k;float f, g, h;... i = j + k;f = g + h; i = j - k;f = g - h; i = k / j; f = g / h; i = k * j; f = g * h; i = k % j; i += j; f += g; i -= j;f -= g; i /= j;f /= g; i *= j;f *= g; i %= j; i = -j;f = -g; i = +j;f = +g; i++;++i; i--;--i;

Relational Operators  Have only boolean result  Works on built-in data types , =, ==, !=  == and != also work with objects (reference check) public class Equivalence { public static void main(String[] args) { Integer n1 = new Integer(15); Integer n2 = new Integer(15); System.out.println(n1 == n2); System.out.println(n1 != n2); }  equals ( ) : for comparing object contents

Logical Operators  AND (&&), OR (||) and NOT (!)  Short circuited public class ShortCircuit { static boolean test1(int val) { System.out.println("test1(" + val + ")"); return val < 1; } static boolean test2(int val) { System.out.println("test2(" + val + ")"); return val < 2; } static boolean test3(int val) { System.out.println("test3(" + val + ")"); return val < 3; } public static void main(String[] args) { if(test1(0) && test2(2) && test3(2)) System.out.println("expression is true"); else System.out.println("expression is false"); }

Bitwise and Shift Operators  Bitwise operators AND operator (&) OR operator (|) XOR operator (^) Bitwise NOT operator (~) is unary operator &=, |=, ^=  Shift operators << Left Shift >> Right Shift >>> Unsigned Right Shift with Zero Extension char, byte, or short will be promoted to int. int will use 5 low-order bits of rhs long will use 6 low-order bits of rhs >=, >>>=

Operators  Ternary if-else operator boolean-exp ? value0 : value1 static int ternary(int i) { return i < 10 ? i * 100 : i * 10; }  The comma operator Only in for loops  String operator + int x = 0, y = 1, z = 2; String sString = "x, y, z "; System.out.println(sString + x + y + z); System.out.println(x + sString);

Operators  Common pitfalls while(x = y) {... } instead of x==y Compiler error unless x and y are boolean if (x&y) { … } instead of x&&y Compiler catches this error  Casting int i = 200; long l = (long)i; // superfluous cast, is not necessary, but clearer code char c = (char) i ; // necessary, otherwise does not compile  Object casts class B extends A { } a = b ; // ok b = a ; // compiler error : incompatible types b = (B) a ; // compiler ok, but run-time check (can throw ClassCastException)

Literals char c = 0xffff; // max char hex value byte b = 0x7f; // max byte hex value short s = 0x7fff; // max short hex value int i1 = 0x2f; // Hexadecimal (lowercase) int i2 = 0X2F; // Hexadecimal (uppercase) int i3 = 0177; // Octal (leading zero) // Hex and Oct also work with long. long n1 = 200L; // long suffix long n2 = 200l; // long suffix (but can be confusing) long n3 = 200; float f1 = 1; float f2 = 1F; // float suffix float f3 = 1f; // float suffix float f4 = 1e-45f; // 10 to the power float f5 = 1e+9f; // float suffix double d1 = 1d; // double suffix double d2 = 1D; // double suffix double d3 = 47e47d; // 10 to the power

Precedence  Unary+, -, ++, --  Arithmetic & Shift+, -, *, /, %, >, >>>  Relational, ==, >=, <=, !=  Logical & Bitwise&&, ||, &, |, ^  ConditionalA > B ? X : Y  Assignment=, *=, +=, etc.

Execution Control  if (Boolean-expression) statement  if (Boolean-expression) statement else statement  while (Boolean-expression) statement  do statement while(Boolean-expression);  for(initialization; Boolean-expression; step) statement

Execution Control  return,  continue, break,  continue label, break label label1: outer-iteration { inner-iteration { //... break; //... continue; //... continue label1; //... break label1; }  switch, case, break switch(integral-selector) { case integral-value1 : statement; break; case integral-value2 : statement; break; … default: statement; }

Constructor  Default Constructor class Rock { Rock() { System.out.println("Creating Rock"); } } public class SimpleConstructor { public static void main(String[] args) { for(int i = 0; i < 10; i++) new Rock(); }  Constructors with Parameters class Rock { Rock(int i) { System.out.println("Creating Rock"+i); } } public class SimpleConstructor { public static void main(String[] args) { for(int i = 0; i < 10; i++) new Rock(i); }

Method Overloading class Tree { int height; Tree() { System.out.println("Planting a seedling"); height = 0; } Tree(int i) { System.out.println("Creating new Tree " + i + " feet tall"); height = i; } void info() { System.out.println("Tree is " + height + " feet tall"); } void info(String s) { System.out.println(s + ": Tree is " + height + " feet tall"); }

Method Overloading  Java distinguishes between overloaded methods according to parameters. void p(string s, int i) { … } void p(int i, string s) { … }  Overloading with primitives void p(byte b) { … } void p(int i) { … } … p(100) ;// p(int) is called  No overloading on return values  Default constructor class Bird { int i; } … new Bird() ; // ok class Hat { int i ; Hat(int x) { i=x; } } … new Hat() ; // compiler error

this  this keyword this.func() return this  Calling constructors from constructors class Flower { Flower(int i) { … } Flower(string s) { … } Flower(int i,string s) { this(i) ;// The first line, and only once … }  this cannot be used in Static methods

Clean up  GC : Garbage Collection  No destructor, only finalize() method  neither GC nor finalize() is guaranteed  System.gc( ) can be called for GC

Member Initialization  Primitive Data types are initialized automatically  Object Reference is initialized to null  Specifying initialization (either in Class definition or in Constructor) class X { boolean b = true; char c = 'x'; Depth d = new Depth(); int i = f(); int j = g(k) ;// Compiler Error int k ; { k = 30 ; … }  Order of initialization, like the order of members in the class definition

Static Initialization  Can be initialized in either way static int i ; static int j = 3 ; static int k ; static { k = 5 ; … }  Static members are initialized when A new object created Any static member is accessed

Array Initialization  int a[] ;  int[] a ;  int[] a = { 1, 2, 3, 4, 5 };  int[] a = new int[5] ;  X[] a = { new X(1), new X(2), new X(5) }  a.length

Multi-dimensional Arrays  int[][] a ;  int[][] a = { { 1, 2, 3, }, { 4, 5, 6, } };  int[][][] a = new int[2][2][4];  int[][][] a = new int[3][][]; a[2] = new int[5][]; a[2][3] = new int[6];  X[][] x = { { new X(1), new X(2) }, { new X(3) } }  X[][] x = new X[3][] ; x[1] = new X[4] ; x[1][2] = new X(54) ;

Array Parameters and Return Values  void f(int[] array) { … } int[] n = new int[100] ; obj.f(n) ;  Arrays are passed as object reference  int[] initNewArray(final int sz, final int val) { int[] arr = new int[sz] ; … ; return arr ; } int[] a = initNewArray(10,4) ;  java.util.Arrays. binary_search( …, … ) equals( …, … ) fill( …, …, …, … ) sort(...)

Arrays  Index from 0  Arrays are created with new  Arrays are treated as regular objects  Boundary errors are found at runtime  Don ’ t use regular arrays for dynamic arrays, it can waste memory and time, and can create non-readable code