Basic Concepts Mehdi Einali Advanced Programming in Java 1.

Slides:



Advertisements
Similar presentations
Programming Languages and Paradigms The C Programming Language.
Advertisements

Chapter 41 Variables and JSP Control Structures JavaServer Pages By Xue Bai.
Control Structures Corresponds with Chapters 3 and 4.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 2 1 Chapter 2 Primitive.
Data Types in Java Data is the information that a program has to work with. Data is of different types. The type of a piece of data tells Java what can.
CS 106 Introduction to Computer Science I 02 / 18 / 2008 Instructor: Michael Eckmann.
Primitive Data Types and Operations. Introducing Programming with an Example public class ComputeArea { /** Main method */ public static void main(String[]
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
Logical Operators Java provides two binary logical operators (&& and ||) that are used to combine boolean expressions. Java also provides one unary (!)
Loops – While, Do, For Repetition Statements Introduction to Arrays
CS 106 Introduction to Computer Science I 10 / 04 / 2006 Instructor: Michael Eckmann.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Primitive Data Types There are exactly eight primitive data types in Java four of them represent integers: byte (class Byte), short (class Short), int.
CONTROL STATEMENTS Lakhbir Singh(Lect.IT) S.R.S.G.P.C.G. Ludhiana.
CSM-Java Programming-I Spring,2005 Control Flow Lesson - 3.
L EC. 03: C ONTROL STATEMENTS Fall Java Programming.
Day 4 Objectives Constructors Wrapper Classes Operators Java Control Statements Practice the language.
Agenda Review User input Scanner Strong type checking Other flow-control structures switch break & continue Strings Arrays 2.
Sadegh Aliakbary Sharif University of Technology Fall 2011.
Advanced Programming in Java
Introduction to Programming Prof. Rommel Anthony Palomino Department of Computer Science and Information Technology Spring 2011.
 Value, Variable and Data Type  Type Conversion  Arithmetic Expression Evaluation  Scope of variable.
Chapter 2: Basic Elements of Java J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition.
1 Do you have a CS account? Primitive types –“ building blocks ” for more complicated types Java is strongly typed –All variables in a Java program must.
Sadegh Aliakbary. Copyright ©2014 JAVACUP.IRJAVACUP.IR All rights reserved. Redistribution of JAVACUP contents is not prohibited if JAVACUP.
DiagrammaticRepresentation Iteration Construct False True Condition Exit from Statement (s) loop Sequence construct Selection construct Statement 1 Statement.
Chapter 2: Using Data.
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.
1 © 2002, Cisco Systems, Inc. All rights reserved. Arrays Chapter 7.
JAVA 0. HAFTA Algorithms FOURTH EDITION Robert Sedgewick and Kevin Wayne Princeton University.
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.
Flow of Control Part 1: Selection
PHP Conditional Statements Conditional statements in PHP are used to perform different actions based on different conditions. Conditional Statements Very.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
Java Programming: From Problem Analysis to Program Design, 5e Chapter 2 Basic Elements of Java.
Using Data Within a Program Chapter 2.  Classes  Methods  Statements  Modifiers  Identifiers.
Copyright © 2012 Pearson Education, Inc. Chapter 6 More Conditionals and Loops Java Software Solutions Foundations of Program Design Seventh Edition John.
CompSci 100E 2.1 Java Basics - Expressions  Literals  A literal is a constant value also called a self-defining term  Possibilities: o Object: null,
Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,
1 Week 6 Branching. 2 What is “Flow of Control”? l Flow of Control is the execution order of instructions in a program l All programs can be written with.
Introduction to Java Java Translation Program Structure
Java Overview. Comments in a Java Program Comments can be single line comments like C++ Example: //This is a Java Comment Comments can be spread over.
August 6, 2009 Data Types, Variables, and Arrays.
J AVA P ROGRAMMING 2 C H 03: C ONTROL STATEMENTS if, for loop (review) switch, while, do while break, continue Fall Java Programming.
Control Flow. Data Conversion Promotion happens automatically when operators in expressions convert their operands For example, if sum is a float and.
Java Programming, Second Edition Chapter Two Using Data Within a Program.
A Simple Java Program //This program prints Welcome to Java! public class Welcome { public static void main(String[] args) { public static void main(String[]
 Control Flow statements ◦ Selection statements ◦ Iteration statements ◦ Jump statements.
Iteration & Loop Statements 1 Iteration or Loop Statements Dept. of Computer Engineering Faculty of Engineering, Kasetsart University Bangkok, Thailand.
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.
REPETITION MTS3033 OBJECT ORIENTED PROGRAMMING 1.
Sadegh Aliakbary Sharif University of Technology Fall 2010.
Basic Concepts Mehdi Einali Advanced Programming in Java 1.
Control structures in C by Dr P.Padmanabham Professor (CSE)&Director Bharat Institute of Engineering &Technology Hyderabad Mobile
Java Programming: From Problem Analysis to Program Design, Second Edition 1 Lecture 1 Objectives  Become familiar with the basic components of a Java.
Chapter 2: Data and Expressions. Variable Declaration In Java when you declare a variable, you must also declare the type of information it will hold.
Lecture 3: More Java Basics Michael Hsu CSULA. Recall From Lecture Two  Write a basic program in Java  The process of writing, compiling, and running.
Control Structures- Decisions. Smart Computers Computer programs can be written to make computers seem smart Making computers smart is based on decision.
Information and Computer Sciences University of Hawaii, Manoa
Java Programming: From Problem Analysis to Program Design, 4e
Chapter 2.
Advanced Programming Behnam Hatami Fall 2017.
Advanced Programming in Java
Java - Data Types, Variables, and Arrays
Chapter 2: Basic Elements of Java
elementary programming
Chapter 3 Selections Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.
Presentation transcript:

Basic Concepts Mehdi Einali Advanced Programming in Java 1

2 agenda Review User input Scanner Strong type checking Other flow-control structures switch break & continue Strings Arrays

3 review Variables Primitive data types Operators Methods Parameter passing Call by value Conditions If, else, else if Loops while do-while for

4 Variables Variables defined and initialized

5 Variables 2 types of variables Class variables(Fields) Local variables Method Variable Method parameter Block Variable There is no global variables Java use static binding for variables

6 Variables A variable always refers to its nearest enclosing binding.(Scoping)

7 User Input Print on console System.out.println How to read from console? Scanner Example: Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); double d = scanner.nextDouble();

8 Example Scanner scanner = new Scanner(System.in); int a = scanner.nextInt(); int b = scanner.nextInt(); long pow = power(a,b); System.out.println(pow);

9 Type Checking Java has a strong type-checking mechanism Some assignment is not permitted int intVal = 2; long longVal =12; intVal = longVal;  Syntax Error longVal = intVal;  OK intVal = (int)longVal;  OK (Type Casting)

10 Direct Type cast The arrows are transitive All other conversions need an explicit cast boolean is not convertible char is a special type

11 Type Conversion Grid

12 Type Conversion N : the conversion cannot be performed Y : the conversion is performed automatically and implicitly by Java C : the conversion is a narrowing conversion and requires an explicit cast Y* : the conversion is an automatic widening conversion, but that some of the least significant digits of the value may be lost by the conversion

13 Example i = ; //a big integer f = i; //f stores and approximation of i System.out.println(f);//output : E8 i = (int) f; System.out.println(i); //output : floating-point types are approximations of numbers They cannot always hold as many significant digits as the integer types

14 Comparison Compare doubles Using == with float or double is an anti- pattern An infinite loop: for (float f = 10f; f != 0; f -= 0.1) { System.out.println(f); }

15 Numeric Assignments Numeric Suffix Double d = d; Float f = 123f; Long l = l; byte b = 127;//Nothing Assignment Overflow Large long to int Lower bits are used No runtime error Large double to integer Brings a max int

16 Operators and cast Division (“/”) operates differently on integers and on doubles!

17 Flow controls

18 Structured programming Sequence Selection If-else switch-case Iteration for while do-while

19 Block Sometimes a group of statements needed to be executed in all or nothing manner It is same as single statement and can be replaced with a method

20 Block Variable

21 If-else Braces is optional for single statement Remember: place braces for clarify for indentation else will bind to last if

22 Short cut Boolean evaluation && vs &, || vs |

23 Loop-1 Constructs Initialize Step Termination condition

24 Loop-2 Watch out infinite loop

25 Switch statement switch (i) { case 1: System.out.println("1"); break; case 2: System.out.println("2"); break; default: System.out.println("default"); }

26 Break Jump out of loop block

27 Continue Stops the execution of the body of the loop and continues from the beginning of the loop

28 Nested loop outer: for (int i = 0; i < 10; i++){ inner: for (int j = 0; j < 10; j++) { if (j == 2){ break outer; } else { System.out.println(i); System.out.println(j); continue inner; }

29 Switch without break

30 Comments Comments are ignored by compiler One-line comment //nextInt = scanner.nextInt(); Multiple-line comment /*nextInt = scanner.nextInt(); for(int i=0;i<nextInt;i++){ System.out.println(i); } */ Javadoc comments /** *... text... */

31 String

32 String A sequence of characters Character: char ch = ‘a’; char ch = ‘1’; char ch = ‘#’; Strings: String st = “Ali”; String st = “123”; String st = “1”; String st = “”; String is not a primitive type

33 String String in C and C++ char* and char[] \0 at the end of String Some functions strlen, strcpy, … String in java is a class String in java is not equal to char[] Constant strings “salam!” “Hellow World!”

34 String and other types String input = "Nader and Simin, A Separation"; char ch = input.charAt(0); int i = input.indexOf("Nader"); int j = input.lastIndexOf("Simin"); String newS = input.replace("Separation", "Reconciliation"); String sth = newS + ch + i + j; System.out.println(sth);

35 String methods charAt concat  plus (+) operator contains startsWith endsWith indesxOf  first index of sth lastIndexOf replace substring length split

36 Immutable String String in java is an immutable class After creating a string, you can not change it If you want to change it, you should create a new string There is no such methods for strings: setCharAt(int) setValue(String) Methods like replace and replaceAll, do not change the value They return a new String

37 example What is the output of this code? String str = "Gholi"; str.replaceAll("li", "lam"); System.out.println(str); String str = "Gholi"; String replaced = str.replaceAll("li", "lam"); System.out.println(replaced);

38 Data Hierarchy Bit Byte Character Word

39 Java Characters Some characters are special characters Special characters are shown using backslash Examples: New line: \n Tab : \t Double-quote : \” Single-quote : \’ Backslash : \\

40 Arrays

41 Array Collections of related data items related data items of the same type Arrays are fixed-length entities they remain the same length once they are created An array is a group of variables called elements containing values that all have the same type The position number of the element is it’s index Array elements are sequentially located in memory

42

43 samples Create an array of 10 integer elements int[] array = new int[10]; int array[] = new int[10];//equal Create an array of n characters char[] characters = new char[n]; Change value of 5’th element array[5] = 12; Retrieving value of n’th element char ch = array[n];

44 Array Creation Shortcut char[] array = new char[3]; array[0] = 'a'; array[1] = 's'; array[2] = 't'; The above code can be rewritten as: char[] array = {'a','s','t'}; Other examples: int[] numbers = {1,2,3,5,9,123}; boolean[] b = {true, true, false, true};

45 Multidimensional Arrays int[][] matrix = new int[3][4]; matrix[2][3] = 2; System.out.println(matrix[2][1]);

46 Unbalanced Multidimensional Array int[][] matrix = new int[3][]; matrix[0] = new int[2]; matrix[1] = new int [5]; matrix[2] = new int [4]; matrix[2][3] = 2; System.out.println(matrix[2][1]); matrix[0][3] = 2;//Runtime Error ArrayIndexOutOfBoundsException

47 Quiz (5 min ) e)exception

48 end