Advanced Programming in Java

Slides:



Advertisements
Similar presentations
Chapter 41 Variables and JSP Control Structures JavaServer Pages By Xue Bai.
Advertisements

1 Chapter 2 Introduction to Java Applications Introduction Java application programming Display ____________________ Obtain information from the.
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.
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.
CSci 142 Data and Expressions. 2  Topics  Strings  Primitive data types  Using variables and constants  Expressions and operator precedence  Data.
CSM-Java Programming-I Spring,2005 Control Flow Lesson - 3.
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.
From C++ to Java A whirlwind tour of Java for C++ programmers.
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
Java Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
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.
Vladimir Misic: Characters and Strings1Tuesday, 9:39 AM Characters and Strings.
CSC 212 Object-Oriented Programming and Java Part 2.
Java Programming, Second Edition Chapter Two Using Data Within a Program.
School of Computer Science & Information Technology G6DICP - Lecture 4 Variables, data types & decision making.
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.
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.
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.
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.
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
Chapter 2 Variables.
String class.
Yanal Alahmad Java Workshop Yanal Alahmad
Object Oriented Programming
Multiple variables can be created in one declaration
Chapter 3 Selections Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved
User input We’ve seen how to use the standard output buffer
Type Conversion, Constants, and the String Object
Java Programming: From Problem Analysis to Program Design, 4e
Primitive Types Vs. Reference Types, Strings, Enumerations
Chapter 2.
Advanced Programming Behnam Hatami Fall 2017.
Starting JavaProgramming
Java - Data Types, Variables, and Arrays
Chapter 2: Basic Elements of Java
Arrays We often want to organize objects or primitive data in a way that makes them easy to access and change. An array is simple but powerful way to.
CMSC 202 Java Primer 2.
elementary programming
Chapter 3 Selections Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.
Fundamental Programming
Chapter 2 Variables.
Comparing Python and Java
Review of Java Fundamentals
Presentation transcript:

Advanced Programming in Java Basic Concepts Mehdi Einali

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

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

Variables Variables defined and initialized

Variables 2 types of variables There is no global variables Class variables(Fields) Local variables Method Variable Method parameter Block Variable There is no global variables Java use static binding for variables Block variable can be defined only when there not upper scope variable in method

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

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

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

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)

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

Type Conversion Grid

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

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

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); }

Numeric Assignments Numeric Suffix Assignment Overflow Double d = 123.54d; Float f = 123f; Long l = 123123 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

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

Flow controls

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

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

Block Variable

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

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

Loop-1 Constructs Initialize Step Termination condition

Watch out infinite loop

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

Break Jump out of loop block

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

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; }

1 2 3 4 5 6 7 8 9 Switch without break

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 ... */

String

String A sequence of characters Character: Strings: 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

String String in C and C++ Some functions String in java is a class 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!”

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);

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

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

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

Data Hierarchy Bit Byte Character Word

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

Arrays

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

samples char ch = array[n]; 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];

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};

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

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

Quiz (5min) a)-ab@d@ b)-ab@d@@ c)-a@d@ d)-abd@ e)exception b

end