Successfully reported this slideshow.
Your SlideShare is downloading. ×

Java Foundations: Data Types and Type Conversion

Ad
Ad
Ad
Ad
Ad
Ad
Ad
Ad
Ad
Ad
Ad
Loading in …3
×

Check these out next

1 of 57 Ad

Java Foundations: Data Types and Type Conversion

Download to read offline

Learn how to use data types and variables in Java, how variables are stored in the memory and how to convert from one data type to another.

Watch the video lesson and access the hands-on exercises here: https://softuni.org/code-lessons/java-foundations-certification-data-types-and-variables

Learn how to use data types and variables in Java, how variables are stored in the memory and how to convert from one data type to another.

Watch the video lesson and access the hands-on exercises here: https://softuni.org/code-lessons/java-foundations-certification-data-types-and-variables

Advertisement
Advertisement

More Related Content

Slideshows for you (20)

Similar to Java Foundations: Data Types and Type Conversion (20)

Advertisement

More from Svetlin Nakov (20)

Recently uploaded (20)

Advertisement

Java Foundations: Data Types and Type Conversion

  1. 1. Java Foundations Data Types and Variables, Boolean, Integer, Char, String, Type Conversion
  2. 2. Your Course Instructors Svetlin Nakov George Georgiev
  3. 3. The Judge System Sending your Solutions for Automated Evaluation
  4. 4. Testing Your Code in the Judge System  Test your code online in the SoftUni Judge system: https://judge.softuni.org/Contests/3294
  5. 5. Numeral Types, Text Types and Type Conversion Data Types and Variables
  6. 6. Table of Contents 1. Data Types and Variables 2. Integer and Real Number Types 3. Type Conversion 4. Boolean Type 5. Character and String Types 7
  7. 7. Data Types
  8. 8.  Computers are machines that process data  Both program instructions and data are stored in the computer memory  Data is stored by using variables How Does Computing Work? 9 10110
  9. 9.  Variables have name, data type and value  Assignment is done by the operator "="  Example of variable definition and assignment  When processed, data is stored back into variables Variables 10 int count = 5; Data type Variable name Variable value
  10. 10.  A data type  Is a domain of values of similar characteristics  Defines the type of information stored in the computer memory (in a variable)  Examples:  Positive integers: 1, 2, 3, …  Alphabetical characters: a, b, c, …  Days of week: Monday, Tuesday, … What Is a Data Type? 11 Name Type Value age int 25 name String "Peter" size double 3.50 Computer memory
  11. 11.  A data type has:  Name (Java keyword)  Size (how much memory is used)  Default value  Example:  Name: int  Size: 32 bits (4 bytes)  Default value: 0 Data Type Characteristics 1 2 int: sequence of 32 bits in the memory int: 4 sequential bytes in the memory
  12. 12.  Always refer to the naming conventions of a programming language  camelCase is used in Java  Preferred form: [Noun] or [Adjective] + [Noun]  Should explain the purpose of the variable (Always ask "What does this variable contain?") Naming Variables 13 firstName, report, config, usersList, fontSize foo, bar, p, p1, populate, LastName, last_name
  13. 13.  Scope - where you can access a variable (global, local)  Lifetime - how long a variable stays in memory Variable Scope and Lifetime 1 4 String outer = "I'm inside the Main()"; for (int i = 0; i < 10; i++) { String inner = "I'm inside the loop"; } System.out.println(outer); // System.out.println(inner); Error Accessible in the main() Accessible only in the loop
  14. 14.  Variable span is how long before a variable is called  Always declare a variable as late as possible (e.g. shorter span) Variable Span 1 5 static void main(String[] args) { String outer = "I'm inside the main()"; for (int i = 0; i < 10; i++) String inner = "I'm inside the loop"; System.out.println(outer); // System.out.println(inner); Error } "outer" variable span
  15. 15.  Shorter span simplifies the code  Improves its readability and maintainability Keep Variable Span Short 1 6 for (int i = 0; i < 10; i++) { String inner = "I'm inside the loop"; } String outer = "I'm inside the main()"; System.out.println(outer); // System.out.println(inner); Error "outer" variable span – reduced
  16. 16. Integer Types in Java int, long, short, byte
  17. 17. 18 Type Default Value Min Value Max Value Size byte 0 -128 (-27) 127 (27-1) 8 bit short 0 -32768 (-215) 32767 (215 - 1) 16 bit int 0 -2147483648 (-231) 2147483647 (231 – 1) 32 bit long 0 -9223372036854775808 (-263) 9223372036854775807 (263-1) 64 bit Integer Types in Java
  18. 18.  Depending on the unit of measure we can use different data types Centuries – Example 1 9 byte centuries = 20; short years = 2000; int days = 730484; long hours = 17531616; System.out.printf("%d centuries = %d years = %d days = %d hours.", centuries, years, days, hours) // 20 centuries = 2000 years = 730484 days = 17531616 hours.
  19. 19.  Integers have range (minimal and maximal value)  Integers could overflow  this leads to incorrect values Beware of Integer Overflow! 20 byte counter = 0; for (int i = 0; i < 130; i++) { counter++; System.out.println(counter); } 1 2 … 127 -128 -127
  20. 20.  Examples of integer literals:  The '0x' and '0X' prefixes mean a hexadecimal value  E.g. 0xFE, 0xA8F1, 0xFFFFFFFF  The 'l' and 'L' suffixes mean a long  E.g. 9876543L, 0L Integer Literals 2 1 int hexa = 0xFFFFFFFF; //-1 long number = 1L; //1
  21. 21.  Write a program that converts meters to kilometers formatted to the second decimal point  Examples: Problem: Convert Meters to Kilometres 22 1852 1.85 798 0.80 Scanner scanner = new Scanner(System.in); int meters = Integer.parseInt(scanner.nextLine()); double kilometers = meters / 1000.0; System.out.printf("%.2f", kilometers);
  22. 22. Real Number Types in Java float and double
  23. 23.  Floating-point types:  Represent real numbers, e.g. 1.25, -0.38  Have range and precision depending on the memory used  Sometimes behave abnormally in the calculations  May hold very small and very big values like 0.00000000000001 and 10000000000000000000000000000000000.0 What are Floating-Point Types? 24
  24. 24.  Floating-point types are:  float (±1.5 × 10−45 to ±3.4 × 1038)  32-bits, precision of 7 digits  double (±5.0 × 10−324 to ±1.7 × 10308)  64-bits, precision of 15-16 digits  The default value of floating-point types:  Is 0.0F for the float type  Is 0.0D for the double type Floating-Point Numbers 25
  25. 25.  Difference in precision when using float and double:  NOTE: The "f" suffix in the first statement!  Real numbers are by default interpreted as double  One should explicitly convert them to float PI Precision – Example 2 6 float floatPI = 3.141592653589793238f; double doublePI = 3.141592653589793238; System.out.println("Float PI is: " + floatPI); System.out.println("Double PI is: " + doublePI); 3. 1415927 3. 141592653589793
  26. 26.  Write a program that converts British pounds to US dollars formatted to 3rd decimal point  1 British Pound = 1.31 Dollars Problem: Pound to Dollars 27 80 104.800 double num = Double.parseDouble(scanner.nextLine()); double result = num * 1.31; System.out.printf("%.3f", result); 39 51.090
  27. 27.  Floating-point numbers can use the scientific notation, e.g.  1e+34, 1E34, 20e-3, 1e-12, -6.02e28 Scientific Notation 28 double d = 10000000000000000000000000000000000.0; System.out.println(d); // 1.0E34 double d2 = 20e-3; System.out.println(d2); // 0.02 double d3 = Double.MAX_VALUE; System.out.println(d3); //1.7976931348623157E308
  28. 28.  Integral division and floating-point division are different: Floating-Point Division 29 System.out.println(10 / 4); // 2 (integral division) System.out.println(10 / 4.0); // 2.5 (real division) System.out.println(10 / 0.0); // Infinity System.out.println(-10 / 0.0); // -Infinity System.out.println(0 / 0.0); // NaN (not a number) System.out.println(8 % 2.5); // 0.5 (3 * 2.5 + 0.5 = 8) System.out.println(10 / 0); // ArithmeticException
  29. 29.  Sometimes floating-point numbers work incorrectly!  Read more about IEEE 754 Floating-Point Calculations – Abnormalities 3 0 double a = 1.0f; double b = 0.33f; double sum = 1.33d; System.out.printf("a+b=%f sum=%f equal=%b", a+b, sum, (a + b == sum)); // a+b=1.33000001311302 sum=1.33 equal = false double num = 0; for (int i = 0; i < 10000; i++) num += 0.0001; System.out.println(num); // 0.9999999999999062
  30. 30. BigDecimal  Built-in Java Class  Provides arithmetic operations  Allows calculations with very high precision  Used for financial calculations 31 BigDecimal number = new BigDecimal(0); number = number.add(BigDecimal.valueOf(2.5)); number = number.subtract(BigDecimal.valueOf(1.5)); number = number.multiply(BigDecimal.valueOf(2)); number = number.divide(BigDecimal.valueOf(2));
  31. 31.  Write a program to enter n numbers and print their exact sum: Problem: Exact Sum of Real Numbers 32 2 1000000000000000000 5 1000000000000000005 2 0.00000000003 333333333333.3 333333333333.30000000003
  32. 32. Solution: Exact Sum of Real Numbers 33 int n = Integer.parseInt(sc.nextLine()); BigDecimal sum = new BigDecimal(0); for (int i = 0; i < n; i++) { BigDecimal number = new BigDecimal(sc.nextLine()); sum = sum.add(number); } System.out.println(sum);
  33. 33. Live Exercises Integer and Real Numbers
  34. 34. Type Conversion Implicit and Explicit Type Conversion
  35. 35.  Variables hold values of certain type  Type can be changed (converted) to another type  Implicit type conversion (lossless): variable of bigger type (e.g. double) takes smaller value (e.g. float)  Explicit type conversion (lossy) – when precision can be lost: Type Conversion 36 float heightInMeters = 1.74f; double maxHeight = heightInMeters; double size = 3.14; int intSize = (int) size; Explicit conversion Implicit conversion
  36. 36.  Write program to enter an integer number of centuries and convert it to years, days, hours and minutes Problem: Centuries to Minutes 37 The output is on one row 1 1 centuries = 100 years = 36524 days = 876576 hours = 52594560 minutes 5 centuries = 500 years = 182621 days = 4382904 hours = 262974240 minutes 5
  37. 37. Solution: Centuries to Minutes 38 int centuries = Integer.parseInt(sc.nextLine()); int years = centuries * 100; int days = (int) (years * 365.2422); int hours = 24 * days; int minutes = 60 * hours; System.out.printf( "%d centuries = %d years = %d days = %d hours = %d minutes", centuries, years, days, hours, minutes); (int) converts double to int The tropical year has 365.2422 days
  38. 38. Boolean Type True and False Values
  39. 39.  Boolean variables (boolean) hold true or false: Boolean Type 4 0 int a = 1; int b = 2; boolean greaterAB = (a > b); System.out.println(greaterAB); // False boolean equalA1 = (a == 1); System.out.println(equalA1); // True
  40. 40.  A number is special when its sum of digits is 5, 7 or 11  For all numbers 1…n print the number and if it is special Problem: Special Numbers 41 20 1 -> False 2 -> False 3 -> False 4 -> False 5 -> True 6 -> False 7 -> True 8 -> False 9 -> False 10 -> False 11 -> False 12 -> False 13 -> False 14 -> True 15 -> False 16 -> True 17 -> False 18 -> False 19 -> False 20 -> False
  41. 41. Solution: Special Numbers 42 int n = Integer.parseInt(sc.nextLine()); for (int num = 1; num <= n; num++) { int sumOfDigits = 0; int digits = num; while (digits > 0) { sumOfDigits += digits % 10; digits = digits / 10; } // TODO: check whether the sum is special }
  42. 42. Character Type Variables Holding a Letter or Special Char 'A'
  43. 43.  The character data type  Represents symbolic information  Is declared by the char keyword  Gives each symbol a corresponding integer code  Has a '0' default value  Takes 16 bits of memory (from U+0000 to U+FFFF)  Holds a single Unicode character (or part of character) The Character Data Type 4 4
  44. 44.  Each character has an unique Unicode value (int): Characters and Codes 4 5 char ch = 'a'; System.out.printf("The code of '%c' is: %d%n", ch, (int) ch); ch = 'b'; System.out.printf("The code of '%c' is: %d%n", ch, (int) ch); ch = 'A'; System.out.printf("The code of '%c' is: %d%n", ch, (int) ch); ch = 'щ'; // Cyrillic letter 'sht' System.out.printf("The code of '%c' is: %d%n", ch, (int) ch);
  45. 45.  Write a program that takes 3 lines of characters and prints them in reversed order with a space between them  Examples: Problem: Reversed Chars 46 A B C C B A 1 L & & L 1
  46. 46. Solution: Reversed Chars 47 Scanner scanner = new Scanner(System.in); char firstChar = scanner.nextLine().charAt(0); char secondChar = scanner.nextLine().charAt(0); char thirdChar = scanner.nextLine().charAt(0); System.out.printf("%c %c %c", thirdChar, secondChar, firstChar);
  47. 47.  Escaping sequences are:  Represent a special character like ', " or n (new line)  Represent system characters (like the [TAB] character t)  Commonly used escaping sequences are:  '  for single quote "  for double quote   for backslash n  for new line  uXXXX  for denoting any other Unicode symbol Escaping Characters 4 8
  48. 48. Character Literals – Example 4 9 char symbol = 'a'; // An ordinary character symbol = 'u006F'; // Unicode character code in a // hexadecimal format (letter 'o') symbol = 'u8449'; // 葉 (Leaf in Traditional Chinese) symbol = '‚'; // Assigning the single quote character symbol = ''; // Assigning the backslash character symbol = 'n'; // Assigning new line character symbol = 't'; // Assigning TAB character symbol = "a"; // Incorrect: use single quotes!
  49. 49. String Sequence of Letters "ABC"
  50. 50. The String Data Type  The string data type  Represents a sequence of characters  Is declared by the String keyword  Has a default value null (no value)  Strings are enclosed in quotes:  Strings can be concatenated  Using the + operator 51 String s = "Hello, Java";
  51. 51.  Strings are enclosed in quotes "":  Format strings insert variable values by pattern: Formatting Strings 52 String file = "C:Windowswin.ini"; The backslash is escaped by String firstName = "Svetlin"; String lastName = "Nakov"; String fullName = String.format( "%s %s", firstName, lastName);
  52. 52.  Combining the names of a person to obtain the full name:  We can concatenate strings and numbers by the + operator: Saying Hello – Examples 5 3 String firstName = "Ivan"; String lastName = "Ivanov"; String fullName = String.format( "%s %s", firstName, lastName); System.out.printf("Your full name is %s.", fullName); int age = 21; System.out.println("Hello, I am " + age + " years old");
  53. 53.  Read first and last name and delimiter  Print the first and last name joined by the delimiter Problem: Concat Names 54 John Smith -> John->Smith Linda Terry => Linda=>Terry Jan White <-> Jan<->White Lee Lewis --- Lee---Lewis
  54. 54. String firstName = sc.nextLine(); String lastName = sc.nextLine(); String delimiter = sc.nextLine(); String result = firstName + delimiter + lastName; System.out.println(result); Solution: Concat Names 55 Jan<->White
  55. 55. Live Exercises Data Types
  56. 56.  …  …  … Summary 57  Variables – store data  Numeral types:  Represent numbers  Have specific ranges for every type  String and text types:  Represent text  Sequences of Unicode characters  Type conversion: implicit and explicit
  57. 57.  …  …  … Next Steps  Join the SoftUni "Learn To Code" Community  Access the Free Coding Lessons  Get Help from the Mentors  Meet the Other Learners https://softuni.org

Editor's Notes

  • Hello, I am Svetlin Nakov from SoftUni (the Software University). Together with my colleague George Georgiev, we shall teach this free Java Foundations course, which covers important concepts from Java programming, such as arrays, lists, methods, strings, classes, objects and exceptions, and prepares you for the "Java Foundations" official exam from Oracle. In this lesson your instructor George will explain and demonstrate the primitive data types in Java, how to declare, initialize and use variables and how to perform type conversions from one data type to another. He will explain the integer types (int and long), the floating-point types (float and double), the text types (char and String) and the special types (boolean and Object). Along with the live coding examples, your instructor will give you some hands-on exercises to gain practical experience with the mentioned coding concepts.
    Are you ready? Let's start!
  • Before the start, I would like to introduce your course instructors: Svetlin Nakov and George Georgiev, who are experienced Java developers, senior software engineers and inspirational tech trainers.

    They have spent thousands of hours teaching programming and software technologies and are top trainers from SoftUni.

    I am sure you will like how they teach programming.


  • Most of this course will be taught by George Georgiev, who is a senior software engineer with many years of experience with Java, JavaScript and C++.

    George enjoys teaching programming very much and is one of the top trainers at the Software University, having delivered over 300 technical training sessions on the topics of data structures and algorithms, Java essentials, Java fundamentals, C++ programming, C# development and many others.
    I have no doubt you will benefit greatly from his lessons, as he always does his best to explain the most challenging concepts in a simple and fun way.



  • Before we dive into the course, I want to show you the SoftUni judge system, where you can get instant feedback for your exercise solutions.

    SoftUni Judge is an automated system for code evaluation. You just send your code for a certain coding problem and the system will tell you whether your solution is correct or not and what exactly is missing or wrong. I am sure you will love the judge system, once you start using it!



  • // Solution to problem "01. Student Information".

    import java.util.Scanner;

    public class Main {
    public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    String name = sc.nextLine();
    int age = Integer.parseInt(sc.nextLine());
    double grade = Double.parseDouble(sc.nextLine());

    System.out.printf("Name: %s, Age: %d, Grade: %.2f",
    name, age, grade);
    }
    }
  • So, you are familiar with the basic use of data types and variables, but in this section, George will explain their meaning in depth and will talk about many interesting topics such as the computer memory, what is the purpose of data types, what other data types are there in Java besides the ones you already know and when to use which. George will give you a detailed explanation of the concepts of "type conversion" and "typecasting" in Java or how to change the variable type at runtime. Remember that you have hands-on exercises to practice the concepts from this course topic. Exercises are more important than the video lesson. Don't skip them!

    Now, let's invite George to teach this course topic.
  • Goes to notes
  • Solution goes to note
  • Goes to exercise
  • Did you like this lesson? Do you want more? Join the learners' community at softuni.org. Subscribe to my YouTube channel to get more free video tutorials on coding and software development.
    Get free access to the practical exercises and the automated judge system for this coding lesson. Get free help from mentors and meet other learners. Join now! It's free. SOFTUNI.ORG

×