Java Tokens & Data types

Slides:



Advertisements
Similar presentations
Chapter 41 Variables and JSP Control Structures JavaServer Pages By Xue Bai.
Advertisements

Types, Variables and Operators Computer Engineering Department Java Course Asst. Prof. Dr. Ahmet Sayar Kocaeli University - Fall 2013.
IntroductionIntroduction  Computer program: an ordered sequence of statements whose objective is to accomplish a task.  Programming: process of planning.
Chapter 4 - Control Structures: Part 1 Outline 4.4Control Structures 4.5The if Selection Structure 4.6The if/else Selection Structure 4.7The while Repetition.
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
Program Elements We can now examine the core elements of programming (as implemented in Java) We focuse on: data types variable declaration and use, constants.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Primitive Data Types There are exactly eight primitive data types in Java four of them represent integers: byte (class Byte), short (class Short), int.
Primitive Types Java supports two kinds of types of values – objects, and – values of primitive data types variables store – either references to objects.
Day 4 Objectives Constructors Wrapper Classes Operators Java Control Statements Practice the language.
Chapter 2: Introducing Data Types and Operators.  Know Java’s primitive types  Use literals  Initialize variables  Know the scope rules of variables.
Java Primitives The Smallest Building Blocks of the Language (corresponds with Chapter 2)
DAT602 Database Application Development Lecture 5 JAVA Review.
Chapter 2: Basic Elements of Java J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition.
Chapter 2 Basic Elements of Java. Chapter Objectives Become familiar with the basic components of a Java program, including methods, special symbols,
1 Do you have a CS account? Primitive types –“ building blocks ” for more complicated types Java is strongly typed –All variables in a Java program must.
Java Software Solutions Lewis and Loftus Chapter 5 1 Copyright 1997 by John Lewis and William Loftus. All rights reserved. More Programming Constructs.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
 The if statement and the switch statement are types of conditional/decision controls that allow your program.  Java also provides three different looping.
Apr, 2011 Dating with Java Larry Li. Objective Hello world program Setup development environment Data types and variables Operators and Expressions Control.
PHY-102 SAPVariables and OperatorsSlide 1 Variables and Operators In this section we will learn how about variables in Java and basic operations one can.
1 Lecture 5 More Programming Constructs Instructors: Fu-Chiung Cheng ( 鄭福炯 ) Associate Professor Computer Science & Engineering Tatung Institute of Technology.
Software Technology - I Tools to do operations.....
 Control Flow statements ◦ Selection statements ◦ Iteration statements ◦ Jump statements.
CSM-Java Programming-I Spring,2005 Fundamental Data Types Lesson - 2.
2: Basics Basics Programming C# © 2003 DevelopMentor, Inc. 12/1/2003.
Java Programming: From Problem Analysis to Program Design, Second Edition 1 Lecture 1 Objectives  Become familiar with the basic components of a Java.
Session 2 Operators, Decisions and Loops. Objectives Operators Casting data Decision marking structures Loops break, continue, return.
Java Basics. Tokens: 1.Keywords int test12 = 10, i; int TEst12 = 20; Int keyword is used to declare integer variables All Key words are lower case java.
Programming Principles Operators and Expressions.
Lecture 3: More Java Basics Michael Hsu CSULA. Recall From Lecture Two  Write a basic program in Java  The process of writing, compiling, and running.
Control Structures- Decisions. Smart Computers Computer programs can be written to make computers seem smart Making computers smart is based on decision.
Java Programming: Guided Learning with Early Objects Chapter 1 Basic Elements of Java.
CIS3931 – Intro to JAVA Lecture Note Set 2 17-May-05.
Data types Data types Basic types
University of Central Florida COP 3330 Object Oriented Programming
Programming in Java Sachin Malhotra, Chairperson, PGDM-IT, IMS Ghaziabad Saurabh Chaudhary, Dean, Academics, IMS Ghaziabad.
Sachin Malhotra Saurabh Choudhary
Yanal Alahmad Java Workshop Yanal Alahmad
Object Oriented Programming
University of Central Florida COP 3330 Object Oriented Programming
Multiple variables can be created in one declaration
Primitive Data, Variables, Loops (Maybe)
Engineering Problem Solving with C++, Etter/Ingber
BY GAWARE S.R. COMPUTER SCI. DEPARTMENT
Fundamental of Java Programming Basics of Java Programming
User input We’ve seen how to use the standard output buffer
JavaScript: Control Statements.
Java Programming: From Problem Analysis to Program Design, 4e
Introduction to C Programming
Java Programming: Guided Learning with Early Objects
Object-Oriented Programming
Operators and Expressions
Operators and Expressions
Arrays, For loop While loop Do while loop
Starting JavaProgramming
Arithmetic operations, decisions and looping
Character Set The character set of C represents alphabet, digit or any symbol used to represent information. Types Character Set Uppercase Alphabets A,
Java - Data Types, Variables, and Arrays
Chapter 2: Basic Elements of Java
Chapter 7 Additional Control Structures
Chapter-3 Operators.
Chapter 6 Control Statements: Part 2
Expressions and Assignment
elementary programming
Module 2 Variables, Data Types and Arithmetic
Chap 7. Advanced Control Statements in Java
Review of Previous Lesson
Problem 1 Given n, calculate 2n
Presentation transcript:

Java Tokens & Data types

Identifiers Can’t be keywords Case-sensitive Begin with and consist of: Letters (a... Z) Numbers (0…9) Underscore (_) Dollar sign ($) Same as C++

Primitive Types boolean 8 bits (1 byte) char 16 bits (2 bytes) byte 8 bits (1 byte) short 16 bits (2 bytes) int 32 bits (4 bytes) long 64 bits (8 bytes) float 32 bits (4 bytes) double 64 bits (8 bytes) Guaranteed to occupy same number of bits regardless of platform unicode.org

Strings Java defines the String class to handle strings A String is a collection of characters treated as a single unit It is not an array of char variables Multiple String constructors String s1 = new String(“Hello World”); String s2 = “Hello World”; http://java.sun.com/j2se/1.5.0/docs/api/

dataType variableName = (dataType) variableToConvert; Type Casting Assigning a value of one type to a variable of another type is known as Type Casting. Syntax:  dataType variableName = (dataType) variableToConvert; Type casting are of two types they are Implicit Casting (Widening) Explicit Casting (Narrowing)

Implicit Casting in Java / Widening / Automatic type conversion Automatic type conversion can happen if both type are compatible and target type is larger than source type.

Explicit Casting in Java / Narrowing When you are assigning a larger type to a smaller type, then Explicit Casting is required.

standard default values In Java, every variable has a default value. If we don’t initialize a variable when it is first created, Java provides default value to that variable type automatically as shown in below table Data Type Default Value (for fields) byte short int long 0L float 0.0f double 0.0d char ‘u0000’ String (or any object) null boolean false

Java – Operators and Expressions The symbols which are used to perform logical and mathematical operations in a Java program are called Java operators. These Java operators join individual constants and variables to form expressions. Operators, functions, constants and variables are combined together to form expressions. Consider the expression A + B * 5. where, +, * are operators, A, B  are variables, 5 is constant and A + B * 5 is an expression.

Types of operators: Java language offers many types of operators. They are, Arithmetic operators Assignment operators Relational operators Logical operators Bit wise operators Conditional operators (ternary operators) Increment/decrement operators Special operators

Arithmetic Operators in Java: Arithmetic operators are used to perform mathematical calculations like addition, subtraction, multiplication, division and modulus in Java programs. S.no Arithmetic Operators Operation Example 1 + Addition A+B 2 – Subtraction A-B 3 * multiplication A*B 4 / Division A/B 5 % Modulus A%B

Assignment Operators in Java In Java programs, values for the variables are assigned using assignment operators. Operators Example Explanation Simple assignment operator = sum = 10 10 is assigned to variable sum Compound assignment operators += sum += 10 This is same as sum = sum + 10 -= sum -= 10 This is same as sum = sum – 10 *= sum *= 10 This is same as sum = sum * 10 /+ sum /= 10 This is same as sum = sum / 10 %= sum %= 10 This is same as sum = sum % 10 &= sum&=10 This is same as sum = sum & 10 ^= sum ^= 10 This is same as sum = sum ^ 10

Relational operators in Java Relational operators are used to find the relation between two variables. i.e. to compare the values of two variables in a Java program. S.no Operators Example  Description 1 > x > y x is greater than y 2 < x < y x is less than y 3 >= x >= y x is greater than or equal to y 4 <= x <= y x is less than or equal to y 5 == x == y x is equal to y 6 != x != y x is not equal to y

Logical operators in Java These operators are used to perform logical operations on the given expressions. S. no Operators Name Example Description 1 && logical AND (x>5)&&(y<5) It returns true when both conditions are true 2 || logical OR (x>=10)||(y>=10) It returns true when at-least one of the condition is true 3 ! logical NOT !((x>5)&&(y<5)) It reverses the state of the operand “((x>5) && (y<5))” If “((x>5) && (y<5))” is true, logical NOT operator makes it false

Bit wise operators in Java These operators are used to perform bit operations. Decimal values are converted into binary values which are the sequence of bits and bit wise operators work on these bits. x y  x|y x & y x ^ y Operator_symbol Operator_name & Bitwise_AND 1 | Bitwise OR ~ Bitwise_NOT ^ XOR   << Left Shift >> Right Shift

Conditional or ternary operators in Java Conditional operators return one value if condition is true and returns another value if condition is false. This operator is also called as ternary operator. Syntax     :         (Condition? true_value: false_value); Example:        (A >100  ?  0 :  1); In above example, if A is greater than 100, 0 is returned else 1 is returned. This is equal to if else conditional statements.

Increment/decrement Operators in Java Increment operators are used to increase the value of the variable by one and decrement operators are used to decrease the value of the variable by one in Java programs. Syntax: Increment operator: ++var_name; (or) var_name++; Decrement operator: --var_name; (or) var_name--;

Difference between pre/post increment & decrement operators in Java: S.no Operator type Operator Description 1 Pre increment ++i Value of i is incremented before assigning it to variable i. 2 Post–increment i++ Value of i is incremented after assigning it to variable i. 3 Pre decrement --i Value of i is decremented before assigning it to variable i. 4 Post_decrement i-- Value of i is decremented after assigning it to variable i.

Operator precedence & associativity Java operators have two properties those are precedence and associativity. Precedence is the priority order of an operator, if there are two or more operators in an expression then the operator of highest priority will be executed first then higher, and then high. For example, in expression 1 + 2 * 5, multiplication (*) operator will be processed first and then addition. It's because multiplication has higher priority or precedence than addition.

Evaluation Order of an Expression In Java when an expression is evaluated, there may be more than one operators involved in an expression. When more than one operator has to be evaluated in an expression Java interpreter has to decide which operator should be evaluated first. Java makes this decision on the basis of the precedence and the associativity of the operators.

Mathematical Functions min(x,y)- Returns the minimum of the two values x and y max(x,y)- Returns the maximum of the two values x and y sqrt(x)- Returns the rounded positive square root of a value. pow(x,y)- Returns the value of x raised to the power of y (xy). exp(x)- Returns e raised to the power of x (ex). round(x)- Returns the closest integer to the argument x. abs(x)- returns the absolute value of x.

Decision making & looping In decision control statements, group of statements are executed when condition is true.  If condition is false, then else part statements are executed. There are 3 types of decision making control statements in Java language.   if statements   if else statements   nested if statements

Decision control statements Syntax Description if if (condition)  { Statements; } In these type of statements, if condition is true, then respective block of code is executed. if…else if (condition)  { Statement1; Statement2; }  else  { Statement3; Statement4; } In these type of statements, group of statements are executed when condition is true.  If condition is false, then else part statements are executed. if else if ladder if (condition1) { Statement1; } else_if(condition2)  { Statement2; }  else  Statement 3; If condition 1 is false, then condition 2 is checked and statements are executed if it is true. If condition 2 also gets failure, then else part is executed.

Loop control statements       Loop control statements in Java are used to perform looping operations until the given condition is true. Control comes out of the loop statements once condition becomes false. There are 3 types of loop control statements in Java language. for while do-while

S.no Loop Name Syntax Description 1 for for (exp1; exp2; expr3) { statements; } Where, exp1 – variable initialization ( Example: i=0, j=2, k=3 ) exp2 – condition checking ( Example: i>5, j<3, k=3 ) exp3 – increment/decrement ( Example: ++i, j–, ++k ) 2 while while (condition) { where,  condition might be a>5, i<10 3 do while do { }while (condition); where, condition might be a>5, i<10

switch case statement in Java Switch case statements are used to execute only specific case statements based on the switch expression. Below is the syntax for switch case statement. switch (expression) { case label1:    statements; break; case label2:    default:    }

break statement in Java Break statement is used to terminate the while loops, switch case loops and for loops from the subsequent execution. Syntax: break;

Example program for break statement in Java:  importjava.lang.*; import java.io.*; class brstmt { public static void main(String args[]) int i;   for(i=0;i<10;i++) if(i==5) System.out.println(“\nComing out of for loop when i = 5”); break; } System.out.println(““+i); Output: 0 1 2 3 4 Coming out of for loop when i = 5

Continue statement in Java Continue statement is used to continue the next iteration of for loop, while loop and do-while loops.  So, the remaining statements are skipped within the loop for that particular iteration. Syntax : continue;

Example program for continue statement in Java: importjava.lang.*; import java.io.*; class constmt { public static void main(String args[]) int i; for(i=0;i<10;i++) if(i==5 || i==6) System.out.println(“\n Skipping from display using continue statement \n”+i); continue; } System.out.println(““+i); Output: 0 1 2 3 4 Skipping 5 from display using continue statement Skipping 6 from display using continue statement 7 8 9

The return statement in Java The return statement is used to explicitly return from a method. That is, it causes program control to transfer back to the caller of the method.

Example program for return statement in Java class ReturnStatement { public static void main(String arg[]) { boolean t = true; System.out.println("Before the return"); // LINE A if(t) return; // return to caller System.out.println("This won't execute"); // LINE B } } OUTPUT Before the return

Nested loops in Java The placing of one loop inside the body of another loop is called nesting. When you "nest" two loops, the outer loop takes control of the number of complete repetitions of the inner loop. While all types of loops may be nested, the most commonly nested loops are for loops.

OUTPUT 0   0 0   1 0   2 1   0 1   1 1   2 2   0 2   1 2   2 3   0 3   1 3   2

Labeled Loops According to nested loop, if we put break statement in inner loop, compiler will jump out from inner loop and continue the outer loop again. What if we need to jump out from the outer loop using break statement given inside inner loop? The answer is, we should define label along with colon(:) sign before loop.  

Syntax of Labelled loop

for-each version of the for loop It is mainly used to traverse array or collection elements. The advantage of for-each loop is that it eliminates the possibility of programming error and makes the code more readable. Syntax of for-each loop: for(data_type variable : array or collection) { }  

Example of for-each version of the for loop class ForEachExample1 { public static void main(String args[]) int arr[]={12,13,14,44}; for(int i:arr) System.out.println(i); } } } Output: 12 13 14 44

Questions Describe any two relational and any two logical operators in Java with simple example. Write general syntax of any two decision making statements and also give its examples. Write a program to check whether an entered number is prime or not. Explain break and continue statements with example. State syntax and describe working of ‘for each’ version of for loop with one example. Define a class having one 3-digit number as a data member. Initialize and display reverse of that number. Explain any four features of Java. Describe ?: (Ternary operator) in Java with suitable example. Explain any two bit-wise operators with example. What is byte code? Explain any two tools available in JDK. What is JVM? What is byte code? ‘?:’ what this operator is called ? Explain with suitable example.

Write a program to accept a number as command line argument and print the number is even or odd. Define JDK. List the tools available in JDK explain any one in detail. Explain: 1) Platform independence 2) Compiled and interpreted features of Java. Write any four mathematical functions used in Java. Write a program to find sum of digits of number. What do mean by typecasting? When it is needed? Write a program to generate Fibonacci series : 1 1 2 3 5 8 13 21 34 55 89. Write a program to print reverse of a number. List eight data types available in java with their storage sizes in bytes. Describe typecasting with one example. What is meant by instance variable and static variable? Describe with example.