This document covers the fundamentals of Java (Java SE 8), focusing on data types, variables, operators, and naming conventions. It explains keywords, identifiers, variable definitions, data types, and operators, along with their syntax and usage. Additionally, it addresses the rules for naming constants and expressions, highlighting the importance of variable scope and initialization.
Java Fundamentals (JavaSE 8) Data, Variables, and Operators Presented by : Eng Marwa Ali Eissa ;) 2
2.
LOGOkeywords Keywords are wordsthat : Are reserved for use by Java. May not be used to name Java applications or objects ,such as classes ,methods or variables. Are case-sensitive and in lowercase
3.
LOGOIdentifiers An identifier isa name that: Identifies a variable, class or method Identifiers must start with either an uppercase or lowercase letter, an underscore (_), or a dollar sign ($). Identifiers cannot contain punctuation, spaces, dashes, or any of the Java technology keywords. Most importantly identifiers are case sensitive. Identifiers cannot begin with a digit (0-9) White space is not permitted. Examples of legal identifiers: age, $salary, _value, __1_value Examples of illegal identifiers : 123abc, -salary , max value
4.
LOGONaming Convention inJava packages names are in lowercase . E.g :java.lang,java.util and com.ourglobalcompany.myproject.model Classes: Names should be in CamelCase is where each new word begins with a capital letter E.g. :CustomerAccount , Employee Methods & Variables : is the same as CamelCase except the first letter of the name is in lowercase E.g.: firstName ,orderNumber void calculateTax() , String getSalary() Constants: Names should be in uppercase. E.g.: DEFAULT_WIDTH , MAX_HEIGHT
5.
LOGOStatements and Blocks Statementsare roughly equivalent to sentences in natural languages. A statement forms a complete unit of execution. The following types of expressions can be made into a statement by terminating the expression with a semicolon (;). Assignment expressions Any use of ++ or -- Method invocations Object creation expressions
6.
LOGOStatements and Blocks MultipleJava statements may be grouped using braces to form a block statement. Block statements are logical units of statements ,usually associated with a specific statement container such as a method or a loop .Java allows to place a block statement within another block
7.
LOGOVariables Variables are namedmemory locations that are used for storing data items of a value of a particular data type or a reference to an object. Variable lives confined to the scope of their definition, which cab be : At the local evlevel inside a method or block of code , they are called local variables At the object instance lel when defined as a Non-static attribute , also called instance variables At the class level when defined as a static attribute , also called class variables Variables in method declarations—these are called parameters.
8.
LOGOVariables Variable Naming Conventions Thevariable naming conversions are the same as those of identifiers Java developers must not use the dollar symbol in a variable. Also, variable names must not start with an underscore Initializing Variables You can assign values to variables in your program during variable declaration. datatype variableName = initvalue; datatype variable1 = initvalue , variable2= initvalue2 , .... , variableN= initvalueN; Uninitialized Variables Attributes (instance or static) are always initialized to a default value local variable must be initialized otherwise the Program does not compile Variable Declaration To declare a variable, you use the syntax : datatype varableName; To Declare multiple variables using A single statement : datatype variable1,variable2 ,variable3 ,..... variableN;
9.
LOGO 9 Data Types inJAVA Value Types (Built in data types – Primitive data types Like: int , float , ..) Reference Types (any other type Like: objects , Interface , array, Enum ..) 5 x int x =5; stack heap Memory ref Data
10.
LOGOPrimitive Data Types sThere are eight primitive data types supported by Java, and they enable you to define variables for storing data that fall into one of three categories: 1. Numeric values integer (byte, short, int, and long) floating-point (float and double) 2. A single Unicode character (char) 3. Logical values (boolean) that can be true or false
11.
LOGOInteger Data Types DataType Size Range Default Value byte 1 byte (8 bits) -27 to 27-1 (-128 to +127 or 256 possible values) 0 short 2 bytes (16 bits) -215 to 215-1 (-32,768 to 32,767 or 65,535 possible values ) 0 int 4 bytes (32 bits) -231 to 231-1 (-2,147,483,648 to 2,147,483,647 or 4,294,967,296 possible Values ) 0 long 8 bytes (64 bits) -263 to 263-1 (- 9,223,372,036854,775,808 to 9,223,372,036854,775,807, or 18,446,744,073,709,551,616 possible values) 0L
12.
LOGOFloating-Point Data Types DataType Size Default Value float 32-bit 0.0f double 64-bit 0.0d Float is mainly used to save memory in large arrays of floating point numbers. Float data type is never used for precise values such as currency. Double data type is generally used as the default data type for decimal values. generally the default choice. Double data type should never be used for precise values such as currency.
13.
LOGOCharacter Type Chardata type is used to store any character. Java uses Unicode to represent characters char data type is a single 16-bit Unicode character. Minimum value is 'u0000' (or 0). Maximum value is 'uffff' (or 65,535 inclusive). Default value : 'u0000' Example : char letterA ='A'
14.
LOGOBoolean Type booleandata type represents one bit of information. There are only two possible values : true and false. This data type is used for simple flags that track true/false conditions. Used to hold the result of an expression that evaluates to either true or false. Default value : false The size of boolean is not defined in the Java specification, but requires at least one bit. Example : boolean one = true
15.
LOGOPrimitive Casting byte short int long float double Implicit Casting Explicit Casting (Automatic Type Conversions) Explicit casting Implicit casting Data loss due to explicit down casting
16.
LOGOLiterals A literal injava is any item that directly represents a particular value . Variables belonging to any primitive types can also be assigned values and treated as literals . Each variable type has a corresponding literal type , such as integer, character, string and boolean Literal
17.
LOGOTypes of Literals Thereare four types of literals in java, which are based on the types of variables present Numeric Literal int ex: 7 double ex: 12.87 , 12e22 , 19E-95 float ex: 12.87f , 123.988F Boolean Literal true or false Character Literal ‘a’ ,’A’,’#’,’3’ ASCII String Literal “hi from Marwa” , “Welcome n in New Horizons”
18.
LOGOEscape Sequences forCharacter Literals Escape Sequence Description t Insert a tab in the text at this point. b Insert a backspace in the text at this point. n Insert a newline in the text at this point. r Insert a carriage return in the text at this point. f Insert a formfeed in the text at this point. ' Insert a single quote character in the text at this point. " Insert a double quote character in the text at this point. Insert a backslash character in the text at this point. d Octal xd Hexadecimal ud Unicode Character
19.
LOGODeclaring Constants AConstant is a variable type in java whose value does not change . Constants are defined using the final keyword followed by the variable declaration. By convention ,constant variable names are in uppercase .If the name is composed of more than one word, the words are separated by an underscore (_). Constants defined in this way cannot be reassigned, and it is a compile - time error if your program tries to do so. EX: final double PI=3.141592653589793; EX: final int FEET_PER_YARD = 3;
20.
LOGOExpressions An expression isa combination of operators (such as addition '+', subtraction '-', multiplication '*', division '/') and operands (variables or literals), that can be evaluated to yield a single value of a certain type 1 + 2 * 3 // evaluated to int 7 int sum, number; sum + number // evaluated to an int value // Evaluated to a double value double principal, interestRate; principal * (1 + interestRate)
LOGOArithmetic Operators Operator MeaningSyntax + Addition X + y ــ Subtraction X - y * Multiplication X * y / Division X / y % Modulus The reminder from a division operation X % y Arithmetic operators are used in mathematical expressions String Concatenation The + operator may used to concatenate the strings together System.out.println("Account Balance is"+ balance);
23.
LOGOCompound Arithmetic AssignmentOperators Operator Expression Meaning += X += y X=X + y =ــ X -= y X=X – y *= X *= y X=X * y /= X /= y X=X / y %= X %= y X=X % y = Simple assignment operator, Assigns values from right side operands to left side operand
24.
LOGORelational Operators Relational Operatorsare symbols user for determining relational comparisons between operands. all expressions created using relational operators will return a boolean value , depending on whether the comparison is true Operator Meaning Syntax == equal to X == y != not equal to X != y > greater than X > y < less than X < y >= greater than or equal to X >= y <= less than or equal to X <= y
25.
LOGOLogical Operators Operator Meaning &logical AND && conditional AND | logical OR || Conditional OR ^ exclusive OR (XOR) ! logical (NOT) Logical Operators evaluate expressions that carry boolean values . The result returned by logical operators is also a boolean value.
LOGOIncrement and DecrementOperators Operator Meaning ++ Increment operator; increase the value of a numeric variable or array element by 1 -- Decrement operator; reduce the value of a numeric variable or array element by 1 Prefix and Postfix Prefix : Placing the operator before the operand causes increment or decrement to occur before the value of the operand is used to evaluate an expression For example : int a=5; int x =++a; both x and a will have the value 6 Postfix : Placing the operator after the operand causes increment or decrement to occur after the value of the operand is used in an expression For example : int a=5; int x =a++; x will have the value of 5 and a will have the value 6
28.
LOGOBitwise Operators Operator Description Binarybitwise AND (&) Returns a 1 if both bits are 1 Binary bitwise OR (|) Returns a 1 if either bit is 1 Binary bitwise XOR (^) Returns a 1 if both bits have different values Unary bitwise complement (~) Changes each bit in its operand to the opposite value Binary left shift (<<) Shifts bits on the left to the left by a distance denoted by the right operand .Fills in zeros Binary right shift (>>) Shifts bits on the left to the right by a distance denoted by the right operand .Fills in the highest bit on the left side. Binary arithmetic and logical shift (>>>) Shifts bits on the left to the right by a distance denoted by the right operand .Fills in zeros
LOGOOperator Precedence Operator precedenceis the order in which operators are evaluated in an expression containing two or more operators Operators with same precedence are calculated from left to right Parentheses alter the order of calculations
#3 Although they are not keywords, you should not use the boolean values true and false or the value null as names in your programs. Note that const and goto have not been used in the Java language up to now, but they are still reserved words and you must not use them as names.
#9 Take note that: Java is a "strongly type" language. A variable is declared with a type. Once the type of a variable is declared, it can only store a value belonging to this particular type. For example, an int variable can hold only integer such as 123, and NOT floating-point number such as -2.17 or text string such as "Hello". Each variable can only be declared once. You can declare a variable anywhere inside the program, as long as it is declared before used. The type of a variable cannot be changed inside the program. The act of declaring a variable allocates a storage (of size capable of holding a value of the type).
#10 The data type of the variable also determines the range of the values that the memory location can hold. Therefore, the amount of memory allocated for a variable depends on its data type. A variable of the primitive data type holds a value whereas a variable of the reference data type holds the reference to an object in memory.
#11 Choice of Data Types for Variables As a programmer, you need to choose variables and decide on the type of the variables to be used in your programs. Most of the times, the decision is intuitive. For example, use an integer type for counting and whole number; a floating-point type for number with fractional part, String for text message, char for a single character, and boolean for binary outcomes. Rules of Thumb Use int for integer and double for floating point numbers. Use byte, short, long and float only if you have a good reason to choose that specific precision. Use int for counting and indexing, NOT floating-point type (float or double). This is because integer type are precise and more efficient in operations. Use an integer type if possible. Use a floating-point type only if the number contains a fractional part.
#12 Java has a class named Integer (note the upper case I in Integer), which defines two constants to represent maximum and minimum values for the int data type, Integer.MAX_VALUE and Integer.MIN_VALUE. For example, int max = Integer.MAX_VALUE; // Assigns maximum int value to max int min = Integer.MIN_VALUE; // Assigns minimum int value to min
#14 String Another commonly-used type is String, which represents texts (a sequence of characters) such as "Hello, world". String is not a primitive type, and will be further elaborated later. In Java, a char is enclosed by single quotes (e.g., 'A', '0'), while a String is enclosed by double quotes (e.g., "Hello"). For example, String message = "Hello, world!"; // strings are enclosed in double-quotes char gender = 'm'; // char is enclosed in single-quotes
#16 boolean can not be cast Casting between primitive & reference data type is not allowed
#29 The bitwise complement is equal to the two's complement of the value minus one. If two's complement arithmetic is used, then NOT x = −x − 1.