Www.javacup.ir Sadegh Aliakbary. Copyright ©2014 JAVACUP.IRJAVACUP.IR All rights reserved. Redistribution of JAVACUP contents is not prohibited if JAVACUP.

Slides:



Advertisements
Similar presentations
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 9 Strings.
Advertisements

Programming Languages and Paradigms The C Programming Language.
Chapter 41 Variables and JSP Control Structures JavaServer Pages By Xue Bai.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 2 1 Chapter 2 Primitive.
Sadegh Aliakbary. Copyright ©2014 JAVACUP.IRJAVACUP.IR All rights reserved. Redistribution of JAVACUP contents is not prohibited if JAVACUP.
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[]
Java Syntax Primitive data types Operators Control statements.
CS 106 Introduction to Computer Science I 10 / 04 / 2006 Instructor: Michael Eckmann.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie June 27, 2005.
Sadegh Aliakbary. Copyright ©2014 JAVACUP.IRJAVACUP.IR All rights reserved. Redistribution of JAVACUP contents is not prohibited if JAVACUP.
Sadegh Aliakbary. Copyright ©2014 JAVACUP.IRJAVACUP.IR All rights reserved. Redistribution of JAVACUP contents is not prohibited if JAVACUP.
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
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 1 Chapter 2 Elementary Programming.
Chapter 2: Basic Elements of Java J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition.
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.
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.
CIS 260: App Dev I. 2 Programs and Programming n Program  A sequence of steps designed to accomplish a task n Program design  A detailed _____ for implementing.
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.
1 © 2002, Cisco Systems, Inc. All rights reserved. Arrays Chapter 7.
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.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Arrays.
Sadegh Aliakbary. Copyright ©2014 JAVACUP.IRJAVACUP.IR All rights reserved. Redistribution of JAVACUP contents is not prohibited if JAVACUP.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
Using Data Within a Program Chapter 2.  Classes  Methods  Statements  Modifiers  Identifiers.
 Pearson Education, Inc. All rights reserved Introduction to Java Applications.
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.
Assignment An assignment statement changes the value of a variable The assignment operator is the = sign total = 55; Copyright © 2012 Pearson Education,
Sadegh Aliakbary. Copyright ©2014 JAVACUP.IRJAVACUP.IR All rights reserved. Redistribution of JAVACUP contents is not prohibited if JAVACUP.
Vladimir Misic: Characters and Strings1Tuesday, 9:39 AM Characters and Strings.
Topics Logical Operators (Chapter 5) Comparing Data (Chapter 5) The conditional operator The switch Statement The for loop Nested Loops.
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[]
Sadegh Aliakbary. Copyright ©2014 JAVACUP.IRJAVACUP.IR All rights reserved. Redistribution of JAVACUP contents is not prohibited if JAVACUP.
Java String 1. String String is basically an object that represents sequence of char values. An array of characters works same as java string. For example:
2: Basics Basics Programming C# © 2003 DevelopMentor, Inc. 12/1/2003.
Chapter 1 Java Programming Review. Introduction Java is platform-independent, meaning that you can write a program once and run it anywhere. Java programs.
CSC Java Programming, Spring, 2010 Week 2: Java Data Types, Control Constructs, and their C++ counterparts.
Basic Concepts Mehdi Einali Advanced Programming in Java 1.
Sadegh Aliakbary Sharif University of Technology Fall 2010.
Basic Concepts Mehdi Einali Advanced Programming in Java 1.
Java Programming: From Problem Analysis to Program Design, Second Edition 1 Lecture 1 Objectives  Become familiar with the basic components of a Java.
1 More about Flow of Control. Topics Debugging Logical Operators (Chapter 5) Comparing Data (Chapter 5) The conditional operator The switch Statement.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Elementary Programming.
1 1 Chapter 2 Elementary Programming. 2 2 Motivations In the preceding chapter, you learned how to create, compile, and run a Java program. Starting from.
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.
CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 11 GEORGE KOUTSOGIANNAKIS 1 Copyright: 2015 Illinois Institute of Technology_ George Koutsogiannakis.
CSE 110: Programming Language I Matin Saad Abdullah UB 1222.
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.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
Information and Computer Sciences University of Hawaii, Manoa
Elementary Programming
Programming in Java Sachin Malhotra, Chairperson, PGDM-IT, IMS Ghaziabad Saurabh Chaudhary, Dean, Academics, IMS Ghaziabad.
Yanal Alahmad Java Workshop Yanal Alahmad
CSC 1051 – Data Structures and Algorithms I
Multiple variables can be created in one declaration
Java Programming: From Problem Analysis to Program Design, 4e
Primitive Types Vs. Reference Types, Strings, Enumerations
Chapter 2.
Advanced Programming Behnam Hatami Fall 2017.
Advanced Programming in Java
Chapter 2: Basic Elements of Java
elementary programming
Presentation transcript:

Sadegh Aliakbary

Copyright ©2014 JAVACUP.IRJAVACUP.IR All rights reserved. Redistribution of JAVACUP contents is not prohibited if JAVACUP is clearly noted as the source in the used case. JAVACUP shall not be liable for any errors in the content, or for any actions taken in reliance thereon. Please send your feedback to 2

Agenda Review User input Scanner Strong type checking Other flow-control structures switch break & continue Strings Arrays 3JAVACUP.ir Contents redistribution is allowed if JAVACUP is noted as the source

Review Variables Primitive data types Operators Methods Parameter passing Call by value Conditions If, else, else if Loops while do-while for 4JAVACUP.ir Contents redistribution is allowed if JAVACUP is noted as the source

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(); 5JAVACUP.ir Contents redistribution is allowed if JAVACUP is noted as the source

Example Scanner scanner = new Scanner(System.in); int a = scanner.nextInt(); int b = scanner.nextInt(); long pow = power(a,b); System.out.println(pow); 6JAVACUP.ir Contents redistribution is allowed if JAVACUP is noted as the source

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) 7JAVACUP.ir Contents redistribution is allowed if JAVACUP is noted as the source

Direct Type Conversion The arrows are transitive All other conversions need an explicit cast boolean is not convertible char is a special type 8 byte char short int long float double boolean JAVACUP.ir Contents redistribution is allowed if JAVACUP is noted as the source

Type Conversion Grid 9JAVACUP.ir Contents redistribution is allowed if JAVACUP is noted as the source

Type Conversion 10 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 JAVACUP.ir Contents redistribution is allowed if JAVACUP is noted as the source

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 11JAVACUP.ir Contents redistribution is allowed if JAVACUP is noted as the source

Floating Point, Some Notes Double.NaN double nan = 0.0/0.0; Infinity double inf = Double.MAX_VALUE*2; Negative infinity double inf = Double.MAX_VALUE*(-2); Double.NEGATIVE_INFINITY Double.POSITIVE_INFINITY Formatting a double System.out.format("min double = %5.2f%n", ff); 12JAVACUP.ir Contents redistribution is allowed if JAVACUP is noted as the source

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); } 13JAVACUP.ir Contents redistribution is allowed if JAVACUP is noted as the source

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 14JAVACUP.ir Contents redistribution is allowed if JAVACUP is noted as the source

Switch statement An alternative to if-else Better structure Before Java 1.7 When the condition is a numeric or an ordinal variable With Java 1.7 Strings are also allowed 15JAVACUP.ir Contents redistribution is allowed if JAVACUP is noted as the source

switch example switch (i) { case 1: System.out.println("1"); break; case 2: System.out.println("2"); break; default: System.out.println("default"); } 16JAVACUP.ir Contents redistribution is allowed if JAVACUP is noted as the source

Scanner scanner = new Scanner(System.in); boolean again = true; while(again){ System.out.println("1: Play"); System.out.println("2: Setting:"); System.out.println("3: Exit"); System.out.print("Enter Your Choice:"); int i = scanner.nextInt(); switch (i) { case 1: play(); break; case 2: setting(); break; case 3: again = false; break; default: System.out.println("Enter a valid number"); } 17JAVACUP.ir Contents redistribution is allowed if JAVACUP is noted as the source

Break Breaks the execution of a loop while(true){ int nextInt = scanner.nextInt(); if(nextInt==0) break;... } 18JAVACUP.ir Contents redistribution is allowed if JAVACUP is noted as the source

Continue Stops the execution of the body of the loop and continues from the beginning of the loop for(int i=0;i<10;i++){ if(i==4)continue; System.out.println(i); } Difference between continue in for and while 19JAVACUP.ir Contents redistribution is allowed if JAVACUP is noted as the source

Nested Loops Scanner scanner = new Scanner (System.in); int nextInt; do{ nextInt = scanner.nextInt(); for(int i=0;i<nextInt;i++){ System.out.println(i); } }while(nextInt>0); How to break or continue from outer loop? 20JAVACUP.ir Contents redistribution is allowed if JAVACUP is noted as the source

Label 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; } 21JAVACUP.ir Contents redistribution is allowed if JAVACUP is noted as the source

Tip of the Day: Indentation int nextInt; do{ nextInt = scanner.nextInt(); for(int i=0;i<nextInt;i++){ System.out.println(i); } }while(nextInt>0); 22JAVACUP.ir Contents redistribution is allowed if JAVACUP is noted as the source

Tip of the Day: Indentation int nextInt; do{ nextInt = scanner.nextInt(); for(int i=0;i<nextInt;i++){ System.out.println(i); } }while(nextInt>0); 23JAVACUP.ir Contents redistribution is allowed if JAVACUP is noted as the source

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... */ 24JAVACUP.ir Contents redistribution is allowed if JAVACUP is noted as the source

Comment Example /** Ali Alavi * If the input is a prime number, it returns true */ public boolean isPrime(int number){ if(number <1) return false; /*if(isEven(number)) return false; */ for(int i=2;i<number/2;i++)//searching for a divisible if(number%i==0)... 25JAVACUP.ir Contents redistribution is allowed if JAVACUP is noted as the source

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 26JAVACUP.ir Contents redistribution is allowed if JAVACUP is noted as the source

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!” 27JAVACUP.ir Contents redistribution is allowed if JAVACUP is noted as the source

Example Scanner scanner = new Scanner(System.in); String input; input = scanner.next(); switch (input) { case "Salam": System.out.println("Hi!"); break; case "Khdahafez": System.out.println("Bye!"); break; default: System.out.println("Ha?!"); break; } System.out.println(input); 28JAVACUP.ir Contents redistribution is allowed if JAVACUP is noted as the source

Example(2) 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); 29JAVACUP.ir Contents redistribution is allowed if JAVACUP is noted as the source

String methods charAt concat  plus (+) operator contains startsWith endsWith indesxOf  first index of sth lastIndexOf replace substring length split 30JAVACUP.ir Contents redistribution is allowed if JAVACUP is noted as the source

Regular Expression Regular Expression or Regex Regex is a way to describe a set of strings Based on their common characteristics Regex can be used to search, edit, or manipulate text You must learn a specific syntax to create regex 31JAVACUP.ir Contents redistribution is allowed if JAVACUP is noted as the source

Regex Examples RegexMeaningExample Salam \dA digit459.Any character2A# [afg]a or f or gafg [a-zA-Z]Range: a through z or A through Z, inclusive Aam Salam|byeSalam or byeSalambye a+One or more aaaaaaaaaaa [a-z]+[\d]*A lowercase string and an optional integer number aliali24a43 32JAVACUP.ir Contents redistribution is allowed if JAVACUP is noted as the source

String and Regex String input = "Nader and Simin"; boolean noDigitString = input.matches("[\\D]+"); System.out.println(noDigitString); String[] array = input.split("[,]"); 33JAVACUP.ir Contents redistribution is allowed if JAVACUP is noted as the source

Regex Usage String input = "Nader and Simin, A Separation."; input = input.replace(".", "*"); //input = Nader and Simin, A Separation* input = input.replaceAll(".", "*"); //input = ****************************** 34JAVACUP.ir Contents redistribution is allowed if JAVACUP is noted as the source

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 35JAVACUP.ir Contents redistribution is allowed if JAVACUP is noted as the source

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); 36JAVACUP.ir Contents redistribution is allowed if JAVACUP is noted as the source

Data Hierarchy Bit Byte Character Word 37JAVACUP.ir Contents redistribution is allowed if JAVACUP is noted as the source

Java Characters A Java character has two bytes Java supports Unicode character set standard ASCII Java uses UTF-16 encoding Other unicode encodings: UTF-8 UTF-16 Other non-unicode encodings Windows JAVACUP.ir Contents redistribution is allowed if JAVACUP is noted as the source

Java Special Characters Some characters are special characters Special characters are shown using backslash Examples: New line: \n Tab : \t Double-quote : \” Single-quote : \’ Backslash : \\ 39JAVACUP.ir Contents redistribution is allowed if JAVACUP is noted as the source

Java Special Characters String s = "Salam!\nI am S\tA"; System.out.println(s); s = "\\ \' \""; System.out.println(s); Salam! I am SA \ ' " 40JAVACUP.ir Contents redistribution is allowed if JAVACUP is noted as the source

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 41JAVACUP.ir Contents redistribution is allowed if JAVACUP is noted as the source

Array 42JAVACUP.ir Contents redistribution is allowed if JAVACUP is noted as the source

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]; 43JAVACUP.ir Contents redistribution is allowed if JAVACUP is noted as the source

Example Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); double numbers[] = new double[n]; for(int i=0;i<numbers.length;i++){ numbers[i] = scanner.nextDouble(); } for(int i=0;i<numbers.length;i++){ double d = numbers[i]; System.out.println(d); } 44JAVACUP.ir Contents redistribution is allowed if JAVACUP is noted as the source

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}; 45JAVACUP.ir Contents redistribution is allowed if JAVACUP is noted as the source

Multidimensional Arrays int[][] matrix = new int[3][4]; matrix[2][3] = 2; System.out.println(matrix[2][1]); 46JAVACUP.ir Contents redistribution is allowed if JAVACUP is noted as the source

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 47JAVACUP.ir Contents redistribution is allowed if JAVACUP is noted as the source

Passing Arrays to Methods public static void main(String[] args) { int[] array = {1,2,-4,0}; System.out.println(max(array)); } static int max(int[] numbers){ if(numbers == null || numbers.length == 0) return -1; int max = numbers[0]; for (int i = 1; i < numbers.length; i++) if(max<numbers[i]) max = numbers[i]; return max; } 48JAVACUP.ir Contents redistribution is allowed if JAVACUP is noted as the source

Multi-Dimensional Array Parameters int determinant(int[][] matrix){…} int [][] matrix = { {1,2}, {3,4}} ; int de = determinant(matrix); void check(int[][] array){…} int [][] unbalanced = { {1,2}, {3,4,5,6,7,8}}; check(unbalanced); boolean f(double[][][] cube){…} 49JAVACUP.ir Contents redistribution is allowed if JAVACUP is noted as the source

Call by Element Values? No If the method has an array parameter Array elements are not copied on method invocations A reference to the array is passed to the method More about this topic  later 50JAVACUP.ir Contents redistribution is allowed if JAVACUP is noted as the source

Exercises Write a method for sorting an array of integers Write a method that compares two arrays returns true if elements of the arrays are equal returns false, otherwise Write a method that returns determinant of a matrix Matrix is a two-dimensional array as the method parameter 51JAVACUP.ir Contents redistribution is allowed if JAVACUP is noted as the source

52JAVACUP.ir Contents redistribution is allowed if JAVACUP is noted as the source