Java is software programming language that rules the software world during 1995 to till date. It is an evergreen programming language. Internet flourished with java.
Size: 1.66 MB
Language: en
Added: Sep 22, 2024
Slides: 58 pages
Slide Content
JAVA
Features of java Simple – to learn and understand Object oriented Robust- Due to- Exception handling mechanism - Memory management Architecture neutral – Any make of the machine, it works Platform independent – Works with any operating system Portable – Works across any combination of h/w and OS Multithreaded Dynamic
Tokens – Parts of a coding language Keywords Variables Constants Identifiers Data types Operators Characters strings Special symbols
Token-1: Keywords Keywords are reserved words, set aside for a purpose. abstract continue for new switch assert default goto package synchronous boolean for if private this break double implements protected throw byte else import public throws case enum instanceof return transient catch extends int short try char final interface static void class Finally long strictfp volatile const float native super while
Token-2 : Variable A name given to a location in memory where any value is stored. A Variable should be declared before use. Syntax: datatype variable_name = value; eg : int a; // 4 bytes of memory is set aside // for storing a value.
Token -3 : Constants A constant is a quantity that doesn’t change .
Token - 4 : Identifiers Each program element in a Java program is given a name called identifier . Names given to identify Variables, constants, arrays, methods, classes etc.,are examples for identifiers. eg : a, x, swap(), m[] etc.
Rules for constructing identifier name s : First character should be an alphabet or underscore. Succeeding characters might be digits or letter. Eg : temp1, temp2. No p unctuation and special characters allowed except underscore. Keywords cannot be used as Identifiers.
Token- 6 : Operators An operator is a symbol, used to perform certain operations on the operands( operands are variables/constants ). Eg : int a=10; int b=20; int c; c=a + b; a and b are called as operands and ‘+’ is the operator
Types of operators Arithmetic operators Relational operators Logical operators Assignment operators Increment and decrement operators Conditional operator Bitwise operators
Arithmetic operators OPERATOR MEANING + plus - minus * Multiplication / Division(returns quotient) % Modulo division(returns remainder)
Relational Operators OPERATOR MEANING > Is greater than < Is less than <= Is less than or equal to >= Is greater than or equal to == Is equal to != Is not equal to
Logical Operators OPERATOR MEANING EXAMPLE && AND a > b && a > c || OR a > b || a > c ! NOT !a
A ssignment 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
Increment and decrement operators Operator Meaning Example ++ Increment by one a++ or ++a means a=a+1 -- Decrement by one a-- or --a means a=a-1
Prefix and postfix Prefix:- First, the variable value is incremented or decremented by one then the expression is evaluated using the new value of the variable. Increment operator : ++ var_name ; Decrement operator : -- var_name ; Postfix:- First, the expression is evaluated then the variable value is incremented or decremented by one. Increment operator : var_name ++; Decrement operator : var_name --;
Difference between pre/post Operator type Operator Description Pre increment ++i Value of i is incremented before assigning it to variable i. Post-increment i ++ Value of i is incremented after assigning it to variable i. Pre decrement – – i Value of i is decremented before assigning it to variable i . Post_decrement i– – Value of i is decremented after assigning it to variable i .
Control structures Instructions are executed one by one in a program. That is called as sequential flow of control. Control structures alter this flow of control. 3 kinds. Branching or conditional statements. Looping or iteration statements. Jumping statements.
Branching statements 5 kinds. if statement if.. else statement If..else..if ladder Nested if ..else statement Switch case statement
If If statement tests a condition, if it is true then a set of statements are executed. Syntax: if(condition) { // statement1; //statement2; . . // statementn ; }
if.. else statement If statement tests a condition ,if it is true it executes a set of statements, if it is false then another set of statements. Syntax: if(condition) { // if part statements; } else { //else part statements; }
if ..else..if ladder syntax : if(condition) { // if part statements; } else if(condition) { //else part statements; } else { //else part }
Nested if else syntax: if(condition) { if(condition ) { // if part statements; } else { //else part statements; } } else { //else part statements; }
Switch ..case statement Tests multiple conditions. Syntax: switch(expression) { case value1: stmts ; break; case value2: stmts ; break; . . default : stmts ; } Whichever case matches with the expression, that case statements execute.
..continued Following can be used as the expression: byte, short, char, int , enum , String (introduced in java 7) ,
Looping statements Repeats a set of statements specified number of times. For while do..while
for loop Syntax: for(initialization ; test ; increment/decrement) { //statements; } Steps in execution of for loop Initialization of the loop counter. Condition is tested. If the test is true then loop statements are executed. When the loop ends the loop counter is incremented Again the condition is tested, if it is true, the loop is executed, if it is false, the loop exits.
for each loop Introduced in java 5 mainly used to traverse array or collection elements. Advantages : It makes the code more readable. It eliminates the possibility of programming errors. Syntax : for( data_type variable : array | collection) { }
Do..while loop Syntax: do{ //statements; }while(condition); Statements are executed until the condition is true. Condition is tested at the end. Statements are executed at least once.
Jumping statements break continue return
Break statement Break statement is used to break out of loops break out of switch statement Syntax: break; Break when used in loops, takes you to the end of the loop.
Continue statement Continue statement allows us to continue the loop, bypassing some of the statements of the loop. Continue when used in loop, takes you to the beginning of the loop. Syntax: continue;
Return statement Return statement allows us to return a value from a method. Syntax: return value;
Arrays An Array is a collection of similar datatypes . Elements of an array are allocated memory in contiguous memory locations. An array is denoted by a pair of square brackets ‘[ ]’. Array index starts with a zero.
..continued Array declaration: Syntax: datatype variable_name []=new datatype [5]; Eg : 1.int arr []=new int [5]; //array of type int and it //allocates space for 5 elements. 2.float arr1[]=new float[10]; // an array of type // float and space for 10 float elements.
..continued Array initialization: 3 ways An element at once An array can be initialized when it is declared Can be initialized from the keyboard
..continued An element at once : int arr []=new int [5] ; arr [0]=1; arr [1]=2; arr [2]=34; arr [3]=4; arr [4]=55; arr 1 55 4 34 2
..continued 2. Declaration and initialization: Initialization can be done at the time of declaration using flower brackets. eg : int arr [3]= {1,2,3}; arr 1 2 3
..continued 3. From the keyboard using for loop and Scanner class method. eg : int a[]=new int [10], i ; Scanner s=new Scanner(System.in); System.out.println (“enter values into a”); for( i =0;i<10;i++) { s.nextInt (); }
Methods A method is a sub program, which performs a particular ‘task’ when ‘called’. A Java class is a set of some variables and some methods. main() is the predefined method from where the execution of a program starts. Two types: predefined and userdefined
..continued Uses of methods: Re- useability Modularity Re-usability: Methods are used to avoid rewriting same code again and again in a program. We can call methods any number of times in a program and from any place in a program for the same task to be performed. Modularity: Dividing a big task into small pieces improves understandability of very large Java programs. A large Java program can easily be tracked when it is divided into methods.
Defining a Method Syntax: method definition method declaration return_type method_name (List of parameters) { //set of statements method body }
Method Definition Methods can be defined in any one of the following 4 different ways. No arguments , No return type . No arguments , With return type . With arguments , No return type . With arguments , With return type . Arguments :- These values are passed from calling method to the called method. Generally these values are called as inputs. Return value :- These values are passed from called method to calling method. Generally these values are called as outputs.
static A keyword Mainly used for memory management Applied to a : Variable Method Block
Static variable used to refer the common property of all objects. gets memory only once in class area at the time of class loading.
Static method belongs to the class rather than object of a class. can be invoked without the need for creating an instance of a class. can access static data member and can change the value of it.
Java static block Is used to initialize the static data member. It is executed before main method at the time of class loading.
Restrictions for static method The static method can not use non static data member or call non-static method directly. ‘this’ and ‘super’ cannot be used in static context.
OOPS Concepts Class Object Encapsulation Abstraction Inheritance Polymorphism
Methods A class contains data members and member methods. A method specifies the behaviour of an object. Methods are defined inside the class. Only member methods can access data members. Methods can be called on objects of the class. Using the dot operator.
Method overloading Number of methods with the same name Different types of parameters Different number of parameters Change in return type does not amount to overloading. One way of implementing polymorphism
Constructor A special method to initialize the objects. Same name as its class. No return type not even void.
Types of constructors Default constructor Parameterised constructor
Default constructor No argument constructor. Compiler provides. only if no other constructor is specified. It initializes: numeric data types are set to 0. char data types are set to null character(‘\0’). reference variables are set to null.
Constructor overloading More than one constructors. Parameterised constructors. Different number of arguments or different types of arguments.