Java Data Types, Operators & Expressions PDF
Document Details
Uploaded by Deleted User
BUP
Jasiya Fairiz Raisa
Tags
Summary
This document is a lecture on Java programming concepts, specifically focusing on data types, operators, and expressions. It covers various aspects such as primitive and non-primitive data types, different types of operators, and examples. The document is suitable for undergraduate-level learners.
Full Transcript
Data Types, Operators & Expressions Lecturer Jasiya Fairiz Raisa Dept. of ICT, BUP Contents Input and Output Variable, Scope and Memory Data Types Wrapper Class Literals Operators Expressions Statements Block Input and Output in Java Standard input stream: Sys...
Data Types, Operators & Expressions Lecturer Jasiya Fairiz Raisa Dept. of ICT, BUP Contents Input and Output Variable, Scope and Memory Data Types Wrapper Class Literals Operators Expressions Statements Block Input and Output in Java Standard input stream: System.in Standard output stream: System.out print(): This method in Java is used to display a text on the console. println(): This method in Java is also used to display a text on the console. It prints the text on the console and the cursor moves to the start of the next line at the console. printf(): The printf() statement may take multiple arguments. System.out.print(parameter); System.out.println(parameter); System.out.printf("Printing simple"+ " integer: x = %d\n", x); Input and Output in Java Variable, Scope and Memory A variable is a container which holds the value while the Java program is executed. A variable is assigned with a data type. Thereare three types of variables in Java: local variable instance variable static variable Variable, Scope and Memory instance variable: Instance variables are fields declared within a class but outside any method. These are non-static variable. Int speed= 20; class variable: A class variable is any field declared with the static modifier; this tells the compiler that there is exactly one copy of this variable in existence, regardless of how many times the class has been instantiated. static int numGears= 9; local variable: A variable declared inside the body of the method is called local variable. Similar to how an object stores its state in fields, a method will often store its temporary state in local variables. The syntax for declaring a local variable is similar to declaring a field. But these variables are defined inside any method. int count = 0; parameter variable: Parameters act as variables inside the method. public static void main(String[] args), here args works as the variable of main method. Variable, Scope and Memory Variable Type Scope Memory Allocation Static - Accessible within the class where it's declared. - Allocated once per class in the method area Variable - Can be accessed via the class name without when the class is loaded. (Class creating an instance. - Retains value for the lifetime of the class (until Variable) - Accessible from all instances of the class. the class is unloaded). - Accessible within instances of the class. - Scoped to the instance (object) where it's - Allocated on the heap for each object instance. Instance declared. - Memory is reclaimed when the object is Variable - Can be accessed by non-static methods and garbage collected. constructors of the class. - Scoped to the block of code where it is - Allocated on the stack. Local declared (e.g., within methods, constructors, or - Memory is reclaimed when the block of code Variable loops). (method/constructor) completes execution. - Not accessible outside this block. - Allocated on the stack during - Scoped to the method or constructor where it is Parameter method/constructor execution. declared. Variable - Memory is reclaimed when the - Used to pass data into methods or constructors. method/constructor completes execution. Data Types In java, there are two types of data types Primitive data types: In Java language, primitive data types are the building blocks of data manipulation. These are the most basic data types available in Java language. Non-primitive data types: Non-primitive types are created by the programmer and is not defined by Java (except for String). Data types Aspect Primitive Types Non-Primitive Types Created by the programmer Definition Predefined in Java. (except for String). Can call methods to perform Method Invocation Cannot call methods. operations. Value Assignment Always has a value. Can be null (no value). Starts with a lowercase letter (e.g., Starts with an uppercase letter Naming Convention int, char). (e.g., Integer, String). Data Types Data Types Java defines eight primitive types of data: byte, short, int, long, char, float, double, and boolean. The primitive types are also commonly referred to as simple types. These can be put in four groups: Integers This group includes byte, short, int, and long, which are for whole-valued signed numbers. Floating-point numbers This group includes float and double, which represent numbers with fractional precision. Characters This group includes char, which represents symbols in a character set, like letters and numbers. Boolean This group includes boolean, which is a special type for representing true/false values. 11 Integers Java defines four integer types: byte, short, int, and long. All of these are signed, positive and negative values. 12 Integers byte: Thesmallest integer type is byte. This is a signed 8-bit type that has a range from −128 to 127. Bytevariables are declared by use of the byte keyword. For example, the following declares two byte variables called b and c: byte b, c; 13 Integers short: shortis a signed 16-bit type. It has a range from −32,768 to 32,767. It is probably the least-used Java type. Here are some examples of short variable declarations: short s; short t; 14 Integers long: long is a signed 64-bit type and is useful for those occasions where an int type is not large enough to hold the desired value. Forexample, the following is a program that computes the number of miles that light will travel in a specified number of days: 15 In 1000 days light will travel about 16070400000000 miles. 16 Characters charin Java is not the same as char in C or C++. In C/C++, char is 8 bits wide. This is not the case in Java. Instead, Java uses Unicode to represent characters. Unicode defines a fully international character set that can represent all of the characters found in all human languages. It is a unification of dozens of character sets, such as Latin, Greek, Arabic, Cyrillic, Hebrew, Katakana, Hangul, and many more. Forthis purpose, it requires 16 bits. Thus, in Java char is a 16-bit type. The range of a char is 0 to 65,536. There are no negative chars. 17 Characters Here is a program that demonstrates char variables: ch1 and ch2: X Y 18 Characters Notice that ch1 is assigned the value 88, which is the ASCII (and Unicode) value that corresponds to the letter X. As mentioned, the ASCII character set occupies the first 127 values in the Unicode character set. ch1 contains X ch1 is now Y 19 Booleans A boolean type is declared with the boolean keyword and can only take the values true or false. A Boolean expression returns a boolean value: true or false. 20 Booleans b is false b is true This is executed. 10 > 9 is true 21 Arrays The general form of a one-dimensional array declaration is: dataType[] arr; (or) dataType []arr; (or) dataType arr[]; Example: int month_days[]; new is a special operator that allocates memory. The general form of new as it applies to one-dimensional arrays appears as follows: array-var = new type [size]; Example: month_days = new int; 22 Arrays Itis possible to combine the declaration of the array variable with the allocation of the array itself, as shown here: int month_days[] = new int; This is the way that you will normally see it done in professionally written Java programs. Let’sreview: Obtaining an array is a two-step process. First, you must declare a variable of the desired array type. Second, you must allocate the memory that will hold the array, using new, and assign it to the array variable. Thus, in Java all arrays are dynamically allocated. 23 Arrays class Testarray{ public static void main(String args[]){ int a[]=new int;//declaration and instantiation a=10;//initialization a=20; a=70; a=40; a=50; //printing array for(int i=0;i>=) x &= 3; // Same as x = x & 3 x = 8; System.out.println("x &= 3 -> x: " + x); x >>= 3; // Same as x = x >> 3 // Bitwise OR assignment (|=) System.out.println("x >>= 3 -> x: " + x); x = 5; x |= 3; // Same as x = x | 3 // Left shift assignment (= 18 || income > 40000) ? "Eligible for Basic Plan" : "Not Eligible for Basic Plan"; System.out.println("Eligibility (OR condition): " + eligibility); Ternary Operator // Nested ternary operator for grade String grade = (score >= 90) ? "A" : (score >= 75) ? "B" : (score >= 50) ? "C" : "F"; System.out.println("Grade: " + grade); // Nested ternary with multiple conditions for job position String jobPosition = (experience >= 10) ? "Senior Manager" : (experience >= 5 && isEmployed) ? "Manager" : (experience < 5 && isEmployed) ? "Junior Manager" : "Intern"; System.out.println("Job Position: " + jobPosition); } } Bitwise Operators TheBitwise operators are used to perform a bit manipulation on numbers. This Operator can be used with any integral type(char, int, short, etc) but it cannot be applied to double and float (The result would probably be an illegal floating point value.). Bitwise Operators public class BitwiseOperatorsExample { public static void main(String[] args) { // Bitwise XOR (^) int a = 5; // Binary: 0101 int xorResult = a ^ b; // Binary: 0110 (6 in decimal) int b = 3; // Binary: 0011 System.out.println("Bitwise XOR (a ^ b): " + xorResult); // Bitwise AND (&) int andResult = a & b; // Binary: 0001 (1 in decimal) // Bitwise NOT (~) System.out.println("Bitwise AND (a & b): " + andResult); int notResult = ~a; // Binary: 1010 (two's complement for -6 in decimal) // Bitwise OR (|) System.out.println("Bitwise NOT (~a): " + notResult); int orResult = a | b; // Binary: 0111 (7 in decimal) } System.out.println("Bitwise OR (a | b): " + orResult); } Shift Operators By shifting the bits of its first operand right or left, a shift operator performs bit manipulation on data. Shift Operators public class ShiftOperatorsExample { public static void main(String[] args) { // Unsigned right shift (>>>) int num = 8; // Binary: 00001000 int negativeNum = -8; // Binary: 11111000 in two's complement (for 8-bit illustration) // Left shift ( 2; System.out.println("Left Shift (num >> 2): " + unsignedRightShiftResult); // Right shift (>>) int rightShiftResult = num >> 2; // Binary: 00000010 (2 } in decimal) } System.out.println("Right Shift (num >> 2): " + rightShiftResult); Instance of operator java instanceof operator is used to test whether the The object is an instance of the specified type (class or subclass or interface). Output Expressions, Statements, Block A Java expression consists of variables, operators, literals, and method calls. In Java, each statement is a complete unit of execution. Expressions are part of statements. A block is a group of statements (zero or more) that is enclosed in curly braces { }. Expressions, Statements, Block public static void main(String[] args){ int marks; marks=88; int gpa= calculateGrade(marks); System.out.print(gpa); } Thank You