Java Basic Structure, Identifiers, Data Types and Operators
Document Details

Uploaded by GratefulDallas8635
University of the East
Tags
Summary
This document provides an introduction to the fundamental concepts of Java programming, covering the basic structure of a Java program, identifiers, data types, and operators. The content is designed to provide a clear understanding of how to write, compile, and execute Java programs, along with best practices for creating understandable and maintainable code.
Full Transcript
Computer Programming 2 Module 2: Java Basic structure, Identifiers, Data types and Operators Basic structure of a Java program Line 1 public class HelloWorld { Line 2 public static void main(String[] args) { Line 3 //Prints "Hello, World"...
Computer Programming 2 Module 2: Java Basic structure, Identifiers, Data types and Operators Basic structure of a Java program Line 1 public class HelloWorld { Line 2 public static void main(String[] args) { Line 3 //Prints "Hello, World" Line 4 System.out.println("Hello, World"); Line 5 } Line 6 } Basic structure explained Line 1: This creates a class called HelloWorld. All class names must start with a capital letter, must use PascalCase. The public word means that it is accessible from any other classes. Line 2: When the main method is declared public, it means that it can also be used by code outside of its class, due to which the main method is declared public. The word static used when we want to access a method without creating its object, as we call the main method, before creating any class objects. The word void indicates that a method does not return a value. main() is declared as void because it does not return a value. main is a method; this is a starting point of a Java program. It is an array where each element of it is a string, which has been named as "args". If your Java program is run through the console, you can pass the input parameter, and main() method takes it as input. Line 3: The compiler ignores comment block. Comment can be used anywhere in the program to add info about the program or code block, which will be helpful for developers to understand the existing code in the future easily. Line 4: This statement is used to print text on the screen as output, where the system is a predefined class, and out is an object of the PrintWriter class defined in the system. The method println prints the text on the screen with a new line. You can also use print() method instead of println() method. All Java statement ends with a semicolon. Here are the most important points to note about the Java programs: You have to keep in mind that, Java code is case sensitive. To write a Java program, you must have to define class first. The name of the class in Java (which holds the main method) is the name of the Java program, and the same name will be given in the filename. As mentioned above in the sample program; the name of the class is "HelloWorld" in which the main method is, then this file will be named "HelloWorld.Java". Identifiers Identifiers are tokens that represent names of variables, methods, classes, and other user-defined program elements. All Java variables must be identified with unique names. These unique names are called identifiers. Identifiers can be short names (like x and y) or more descriptive names (age, sum, totalVolume). Note: It is recommended to use descriptive names in order to create understandable and maintainable code. The general rules for constructing names for an identifier (unique identifiers) are: Identifiers must begin with either a letter, an underscore “_”, or a dollar sign “$”. Letters may be lower or upper case. Subsequent characters may use numbers 0 to 9. Identifiers cannot use Java keywords like class, public, void, etc. Java Identifiers Best Practices For names of classes, capitalize the first letter of the identifier. Example: AnExampleOfClassName For names of methods and variables, the identifier should start with a lower-case letter. Example: anExampleOfMethodName For constants use all capitals and separate words with underscores. Example: EXAMPLE_OF_A_CONSTANT Avoid using underscores at the start of the identifier such as _read or _write. A variable is an item of data used to store the state of objects. A variable has a: Data type The data type determines the type of value that the variable can hold. Name The variable name must follow rules for identifiers. Data Types A data type is an attribute of data which tells the compiler or interpreter how the programmer intends to use the data. Data types are divided into two groups: Primitive data types Non-primitive data types Data type Size Description byte 1 byte Stores whole numbers from -128 to 127 short 2 bytes Stores whole numbers from -32,768 to 32,767 int 4 bytes Stores whole numbers from -2,147,483,648 to 2,147,483,647 long 8 bytes Stores whole numbers from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 float 4 bytes Stores fractional numbers. Sufficient for storing 6 to 7 decimal digits double 8 bytes Stores fractional numbers. Sufficient for storing 15 decimal digits boolean 1 bit Stores true or false values char 2 bytes Stores a single character/letter or ASCII values Primitive Data Types Primitive data type specifies the size and type of variable values, and it has no additional methods. o Integer types Stores whole numbers, positive or negative (such as 123 or -456), without decimals. Valid types are byte, short, int and long. Which type you should use, depends on the numeric value. Byte The byte data type can store whole numbers from -128 to 127. This can be used instead of int or other integer types to save memory when you are certain that the value will be within -128 and 127. Short The short data type can store whole numbers from -32,768 to 32,767. Int The int data type can store whole numbers from -2,147,483,648 to 2,147,483,647. In general, the int data type is the preferred data type when we create variables with a numeric value. Long The long data type can store whole numbers from 9,223,372,036,854,775,808 to 9,223,372,036,854,775,807. This is used when int is not large enough to store the value. o Floating point types Represents numbers with a fractional part, containing one or more decimals. There are two types: float and double. Float The float data type can store fractional numbers from 3.4e−038 to 3.4e+038. Double The double data type can store fractional numbers from 1.7e−308 to 1.7e+308. Use float or double? The precision of a floating point value indicates how many digits the value can have after the decimal point. The precision of float is only six or seven decimal digits, while double variables have a precision of about 15 digits. Therefore it is safer to use double for most calculations. o Boolean A boolean data type is declared with the boolean keyword and can only take the values true or false. o Characters The char data type is used to store a single character. The character must be surrounded by single quotes, like 'A' or 'c': Non-Primitive Data Types Non-primitive data types are called reference types because they refer to objects. The main difference between primitive and non-primitive data types are: Primitive types are predefined (already defined) in Java. Non-primitive types are created by the programmer and is not defined by Java (except for String). Non-primitive types can be used to call methods to perform certain operations, while primitive types cannot. A primitive type has always a value, while non-primitive types can be null. A primitive type starts with a lowercase letter, while non-primitive types starts with an uppercase letter. The size of a primitive type depends on the data type, while non- primitive types have all the same size. Examples of non-primitive types are Strings, Arrays, Classes, Interface, etc. o Strings The String data type is used to store a sequence of characters (text). String values must be surrounded by double quotes. Expressions An expression is a statement that can convey a value. Some of the most common expressions are mathematical, such as in the following source code example: int number = 4; int anotherNumber = number; int product = number * anotherNumber; All three of these statements can be considered expressions - they convey values that can be assigned to variables. The first assigns the literal 4 to the variable number. The second assigns the value of the number variable to the anotherNumber variable. The multiplication operator (*) is used to multiply the number integer and anotherNumber integer, and the expression produces the result of the multiplication. This result is stored in the product integer variable. Operators An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations. Java is rich in built-in operators and provide the following types of operators: 1. Unary Operators 2. Arithmetic operators 3. Assignment operators 4. Relational operators 5. Logical operators Unary Operators Unary operators are used with only one operand. For example, ++ is a unary operator that increases the value of a variable by 1. Operator Name Description + Unary plus Convert the operand into a number - Unary minus Inverts the sign of an expression ++ Increment operator Increments value by 1 -- Decrement operator Decrements value by 1 Arithmetic Operators Arithmetic operators are used to perform common mathematical operations. Operator Name Description + Addition Adds together two values - Subtraction Subtracts one value from another * Multiplication Multiplies two values / Division Divides one value by another % Modulus Returns the division remainder Assignment Operators Assignment operators are used to assign values to variables. Operator Example Equivalent to = a = b; a = b; += a += b; a = a + b; -= a -= b; a = a - b; *= a *= b; a = a * b; /= a /= b; a = a / b; %= a %= b; a = a % b; Note: a and b variables were used to save space. Relational Operators A relational operator is used to check the relationship between two operands. Operator Meaning Example == Is Equal To 3 == 5 gives us false != Not Equal To 3 != 5 gives us true > Greater Than 3 > 5 gives us false < Less Than 3 < 5 gives us true >= Greater Than or Equal To 3 >= 5 give us false