1 / 69

Java Basics

introduction to java and simple programs practice

Download Presentation

Java Basics

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Basic Java Elements

  2. Hello World Program, Again // My First Program!! publicclass HelloWorld { public static void main(String[] args){ System.out.println(“Hello World!”); } }

  3. Identifiers: Syntax • Identifiers are the words a programmer uses in a program • Identifier syntactic rules: • Can be made up of any length of • letters • digits • underscore character (_) • dollar sign ($) • Cannot begin with a digit • Java is case sensitive • Useranduserare completely different identifiers

  4. Identifiers: Semantics • Identifiers names can come from the following sources • Fixed in Java as reserved words • public, class, static, void, method, … • Chosen by the programmer to denote something • HelloWorld, main, args • Chosen by a programmer whose code we use: • String, System, out, println

  5. Naming style • The correctness of the program is not affected by the names used public class X7_65Tx { … } • Names play a central role in the readability of the program • They are part of its documentation • They should thus be chosen carefully • BankAccount, size, numberOfElements • Follow conventions in choosing names!

  6. White Space • Spaces, blank lines, and tabs are collectively called white space • White space is used to separate words and symbols in a program • Extra white space is ignored • A valid Java program can be formatted many different ways • Programs should be formatted to enhance readability, using consistent indentation

  7. Valid, but bad Indentation public class HelloWorld { public static void main(String[] args) { System.out.println(“Hello World!”) ;}}

  8. Comments • Comments are ignored and are treated as white space • They should be written to enhance readability • Explain what a piece of code does (its interface) • Explain any special tricks, limitations, … • Java has three comment formats: • // comment to end of line • /* comment until closing */ • /** API specification comment */

  9. Lesson 2 - Basic Java Elements Unit B2 - Variables and Data Types

  10. Variables • A variable is a location in memory that can hold values of a certain datatype • Each variable must be declared before it is used • The declaration allocates a location in memory to hold values of this type • Variable types can be • primitive • reference to an object

  11. VariableExample Program public class VariableExample { public static void main(String[] args){ int x; x = 3; System.out.println(x); x = 4; System.out.println(x); } }

  12. VariableExample Program (2) public class VariableExample { public static void main(String[] args){ int x; x = 3; System.out.println(x); x = 4; System.out.println(x); } } x

  13. VariableExample Program (3) public class VariableExample { public static void main(String[] args){ int x; x = 3; System.out.println(x); x = 4; System.out.println(x); } } 3 x

  14. VariableExample Program (4) public class VariableExample { public static void main(String[] args){ int x; x = 3; System.out.println(x); x = 4; System.out.println(x); } } 3 x

  15. VariableExample Program (5) public class VariableExample { public static void main(String[] args){ int x; x = 3; System.out.println(x); x = 4; System.out.println(x); } } 4 x

  16. VariableExample Program (6) public class VariableExample { public static void main(String[] args){ int x; x = 3; System.out.println(x); x = 4; System.out.println(x); } } 4 x

  17. Primitive Data Types • A data type is defined by a set of values and the operators you can perform on them • The Java language has several predefined types, called primitive data types • The following reserved words represent the eight different primitive data types: • byte, short, int, long, float, double, boolean, char

  18. Integers • There are four integer data types. They differ by the amount of memory used to store them

  19. Floating Point • There are two floating point types

  20. Characters • Acharvalue stores a single character from the Unicode character set • A character set is an ordered list of characters • ‘A’, ‘B’, ‘C’, … , ‘a’, ‘b’, … ,‘0’, ‘1’, … , ‘$’, … • The Unicode character set uses 16 bits per character, allowing for 65,536 unique characters • It is an international character set, containing symbols and characters from many world languages • The ASCII character set is a subset of Unicode • ASCII is the current standard (outside of Java)

  21. Boolean • Abooleanvalue represents a true/false condition. • It can also be used to represent any two states, such as a light bulb being on or off • The reserved wordstrueandfalseare the only valid values for a boolean type

  22. Variable Declarations • The syntax of a variable declaration is data-type variable-name; • For example • Multiple variables can be declared on the same line • Variables can be initialized (given an initial value) in the declaration int total; long total, count, sum; int total = 0, count = 20; double unitPrice = 57.25;

  23. Variable Declaration Example public class DeclarationExample { public static void main (String[] args) { int weeks = 14; long numberOfStudents = 120; double averageFinalGrade = 78.6; System.out.println(weeks); System.out.println(numberOfStudents); System.out.println(averageFinalGrade); } }

  24. More Variable Examples double pi, conversionRate, temprature; long salary; boolean isOn; char c; pi = 3.14159; isOn = false; c = ‘A’; salary = 34000; isOn = true;

  25. Constants • We may declare that a variable is a constant and its value may never change. • Advantages: • readability • efficiency • error detection final double PI = 3.14159; final int CHINA_OLYMPICS_YEAR = 2008;

  26. Lesson 2 - Basic Java Elements Unit B3 - Expressions

  27. Assignment Statements • An assignment statement takes the following form variable-name = expression; • The expression is first evaluated • Then, the result is stored in the variable, overwriting the value currently stored in the variable

  28. Arithmetic Operators • An operator is a mapping that maps one or more values to a single value: • Binary Operators: a + b adds a and b a - b subtracts b from a a * b multiplies a and b a / b divides a by b a % b the reminder of divining a by b • Unary Operator: -a The negation of a

  29. Pounds to Kg conversion public class PoundsToKg { public static void main(String[] args){ double weightInPounds = 200.0; final double KILOS_IN_POUND = 0.455; double weightInKg; weightInKg = weightInPounds * KILOS_IN_POUND ; System.out.println(weightInKg); } }

  30. Pounds to Kg conversion 2 public class PoundsToKg2 { public static void main(String[] args){ final double KILOS_IN_POUND = 0.455; System.out.println(200.0 * KILOS_IN_POUND); } }

  31. Integer Division • When division is performed on integers (byte, short, int, long), the result is truncated to an integer. int j = 5; double x = 5.0, y; System.out.println(j / 2); // 2 System.out.println(x / 2.0); // 2.5 System.out.println(5 / 2); // 2 y = j / 2 ; // 2

  32. Complex Expressions • Expressions can combine many operators and operands • Examples: x -34 weight * 2.73 2 * PI * r a - (7 – b) 1 + 2 + 3 + 4 (x + y) * (2 - z + (5 - q)) * -(1-x)

  33. Operator Precedence • Multiplication, division, and remainder (%) have a higher precedence than addition and subtraction. • Operators with same precedence evaluate from left to right. • Parenthesis can be used to force order of evaluation.

  34. Operator Precedence Examples

  35. Conversions • Data types can be mixed in an expression • When the expression is evaluated one type is converted to another • Data is converted to a wider type in three cases • assignment conversion • arithmetic promotion • casting • Can be converted to a narrower type only by casting • List of types from narrowest to widest: Narrow … Wide byte short int long float double

  36. Conversion Examples double f, x; int j; f = 5; f = 5.0 / 2; f = x * j; f = 5 / 2; f = (float) j / 5; j = (int) f; j = (int) 5.0 / 2.0;

  37. Lesson 2 - Basic Java Elements Unit B4 - Objects and Method Invocation

  38. Reference Types • Variables can be declared to be of an object type. In this case they hold a reference to an object of this type (class). Turtle t; String myName; Date today; myName t today Memory

  39. Creating Objects • Objects are created by invoking a constructor of the class. Constructors may accept parameters. Date today; today = new Date(12345);// mSec since 1.1.1970 Turtle t = new Turtle();

  40. Creating Objects (2) • Objects are created by invoking a constructor of the class. Constructors may accept parameters. Date today; today = new Date(12345);// mSec since 1.1.1970 Turtle t = new Turtle(); today

  41. Creating Objects (3) • Objects are created by invoking a constructor of the class. Constructors may accept parameters. Date today; today = new Date(12345);// mSec since 1.1.1970 Turtle t = new Turtle(); today 12345

  42. Creating Objects (4) • Objects are created by invoking a constructor of the class. Constructors may accept parameters. Date today; today = new Date(12345);// mSec since 1.1.1970 Turtle t = new Turtle(); t today 12345

  43. Strings Strings are objects that are treated by the compiler in special ways: • Can be created directly using “xxxx” • Can be concatenated using + String myName = “John Jones”; String hello; hello = “Hello World”; hello = hello + “!!!!”; int year = 2008; String s = “See you in China in “ + year;

  44. Method invocations • You may invoke methods on an object. Methods may receive parameters. • Methods may also return values. Turtle leonardo = new Turtle(); leoardo.moveForward(100); String lennon = “John Lennon”; int len = lennon.length(); char initial = lennon.charAt(5);

  45. APIs • To use an object you only need to know its application programmer interface (API). • The API of an object class includes a description of: • all available constructors and methods and what they do • the parameters they take and the values that they return • The API is usually given in a special format called javadoc.

  46. Javadoc example

  47. Javadoc example (2)

  48. Class Libraries • A class library is a collection of classes that we can use when developing programs • There is a standard class library that comes with every Java environment. • Class Libraries are organized into packages • java.net, java.lang, java.io, ... • To use classes from a package you must either • Import the package • Or, use a fully qualified class name import java.io.*; File f = new File(“John”); java.io.File f = new java.io.File (“John”);

  49. RandomNumbers.java import java.util.Random; public class RandomNumbers { public static void main (String[] args){ Random generator = new Random(); int num = generator.nextInt(); System.out.println ("A random int: " + num); num = generator.nextInt(); System.out.print(“Another one: “ + num); } }

  50. Lesson 2 - Basic Java Elements Unit B5 - Input and Output

More Related