java notes 1 - operators control-flow
Post on 13-Jan-2017
52 Views
Preview:
TRANSCRIPT
Java - BasicsPrepared byMohammed SikanderTechnical LeadCranes Varsity
Language BasicsVariablesOperatorsControl-flowArrays
mohammed.sikander@cranessoftware.com
3
Converting Ideas to Program
mohammed.sikander@cranessoftware.com
4
C++ Compilation Process
mohammed.sikander@cranessoftware.com
5
JAVA Compilation Process
mohammed.sikander@cranessoftware.com
6
First Java Program
mohammed.sikander@cranessoftware.com
7
The class can be public [not compulsory]
main should be public [compulsory]
main should be static [compulsory]
return type of main should be void [compulsory]
Argument of String [] is compulsory.
only the order of public and static can be swapped.
mohammed.sikander@cranessoftware.com
8
mohammed.sikander@cranessoftware.com
9
If class is public, filename should match class name.
If class is not public, filename can be different.
mohammed.sikander@cranessoftware.com
10
javac FirstProgram.java
Java SecondProgram
mohammed.sikander@cranessoftware.com
11
Naming ConventionsName Conventionclass Names hould start with uppercase letter and
be a noune.g. String, Color, Button, System, Thread etc.
interface Name should start with uppercase letter and be an adjective e.g. Runnable, Remote, ActionListener etc.
method Name should start with lowercase letter and be a verb e.g. actionPerformed(), main(), print(), println() etc.
variable Name should start with lowercase letter e.g. firstName, orderNumber etc.
package Name should be in lowercase letter e.g. java, lang, sql, util.
Constants Name should be in uppercase letter. e.g. RED, YELLOW, MAX_PRIORITY etc.
mohammed.sikander@cranessoftware.com
12
CamelCase in java naming conventionsJava follows camelcase syntax for
naming the class, interface, method and variable.
If name is combined with two words, second word will start with uppercase letter always
actionPerformed( ), firstName, ActionEvent, ActionListener etc.
mohammed.sikander@cranessoftware.com
13
Variables naming - RulesAll variable names must begin with a
letter, an underscore ( _ ), or a dollar sign ($).
[a-z/_/$] [a-z/_/$/0-9]Case sensitive – similar to c/c++
Samples of acceptable variable names: YES
Samples of unacceptable variable
names: NOGrade Grade(Test)GradeOnTest GradeTest#1Grade_On_Test 3rd_Test_GradeGradeTest Grade Test (has a
space) int $a = 5; int a$b = 8; int _x = 4; int _ = 9;
mohammed.sikander@cranessoftware.com
14
Variable naming – GuidelinesThe convention is to always use a
letter of the alphabet. The dollar sign and the underscore are discouraged.
Variable should begin with lowercase, multiple word variable can use camelCasing.
All characters in uppercase are reserved for final(constants)
mohammed.sikander@cranessoftware.com
15
mohammed.sikander@cranessoftware.com
16
DatatypesByte - 1 byteShort - 2 byteInt - 4Long - 8Float - 4 (IEEE 754)Double - 8 (IEEE 754)Char - 2 (unicode)Boolean - 1 (size undefined)Note : java does not support unsigned.
mohammed.sikander@cranessoftware.com
17
LITERALS Integer literals Decimal [1-9][0-9]Octal 0[0-7]Hexadecimal 0x[0-9,A-F]Binary (JAVA SE7) 0b[0-1]Underscore can appear in literals (JAVA SE7)long creditCardNum =
1234_5678_9012_3456L; Floating-point literals Double 4.5 or 4.5d 1.23e2Float4.5f 1.23e2f
mohammed.sikander@cranessoftware.com
18
Write the Outputclass ArithmeticOperation {
public static void main(String [] args ) {
byte a = 5; byte b = 10; byte sum = a + b;
System.out.println("Sum = " + sum); }
}
int sum = a + b;byte sum = (byte)(a + b);
mohammed.sikander@cranessoftware.com
19
Write the Output
Java Programclass ArithmeticOperation {
public static void main(String [] args ) {float res = 9 % 2.5f;System.out.println("res = " + res);}
}
C/ C++ Programint main( ){
float res = 9 % 2.5f;printf(" %f " ,res);
}
mohammed.sikander@cranessoftware.com
20
Arithmetic Operatorsint / int => intfloat / int => floatbyte + byte => int% operator can be applied to
float-typesEg : 5.0 % 2.4 = 0.29 % 2.5 => 1.5; 10 % 2.5 => 0
mohammed.sikander@cranessoftware.com
21
Outputclass ArithmeticOperation {
public static void main(String [] args ) { byte a = 5; byte b = 10; int sum = a + b; byte diff = (byte)(a – b);System.out.println("Sum = " + sum); System.out.println(“diff = " + diff); }
}
mohammed.sikander@cranessoftware.com
22
Conversion from Small to Largepublic class Conversion {public static void main(String args[]) {
byte b = 12;int i = 300;double d = 323.142;System.out.println("\nConversion of byte to
int.");i = b;System.out.println("i and b " + i + " " + b);System.out.println("\nConversion of int to
double.");d = i;System.out.println("d and i " + d + " " + i);
}}
mohammed.sikander@cranessoftware.com
23
Conversion from Large to Smallpublic class Conversion {public static void main(String args[]) {
byte b;int i = 300;double d = 323.142;System.out.println("\nConversion of int to byte.");b = (byte) i;System.out.println("i and b " + i + " " + b);System.out.println("\nConversion of double to int.");i = (int) d;System.out.println("d and i " + d + " " + i);System.out.println("\nConversion of double to byte.");b = (byte) d;System.out.println("d and b " + d + " " + b);
}}
mohammed.sikander@cranessoftware.com
24
Write the Outputpublic class ByteDemo { public static void main(String [] args) { byte x = 127; System.out.println(x); x++; System.out.println(x); }}
mohammed.sikander@cranessoftware.com
25
Code to Print ASCII / UNICODE Value of a Character public class CharAsciiValue { public static void main(String[]
args) { char a = 'A'; System.out.println(a + " " +
(int)a); }}
mohammed.sikander@cranessoftware.com
26
Question
Consider the statement double ans = 10.0+2.0/3.0−2.0∗2.0; Rewrite this statement, inserting
parentheses to ensure that ans = 11.0 upon evaluation of this statement.
mohammed.sikander@cranessoftware.com
27
What should be the datatype of res variable?public static void main( String []
args){
int a = 5;int b = 10;
____ res = a > b;System.out.println(res);
}
mohammed.sikander@cranessoftware.com
28
int main( ){
int a = 5;if(a)
printf(“True");else
printf(“False”);}
public static void main(String [] args)
{int a = 5;if(a)System.out.print("TRUE");elseSystem.out.print(“FALSE");
}
mohammed.sikander@cranessoftware.com
29
Relational Operators Result of Relational operators is of type boolean. int x = 5 > 2;//In valid – cannot assign boolean to int.
boolean flag = false; if(flag) { }
if(flag = true) { } int x = 5; if(x = 0) { }
mohammed.sikander@cranessoftware.com
30
Logical Operators&& , || - Short-circuiting operators, Same as C & , | - evaluates both condition.
if(++x > 5 & ++ y > 5){}Both x and y are updated
if(++x > 5 && ++ y > 5){}Only x is updated.
mohammed.sikander@cranessoftware.com
31
Write the Output
Try with following Changes 1. Change the value of x to 8.2. Replace && with &3. Try with OR Operators (| | and | )
mohammed.sikander@cranessoftware.com
32
Bitwise OperatorsCan be applied on integral types only& , | , ^ , ~, >> , << , >>> >>> (unsigned right shift)
If left and right are boolean, it is relational.
(a > b & a > c)
If left and right are integral, it is bitwise.(a & c)
mohammed.sikander@cranessoftware.com
33
To print in Binary FormInteger.toBinaryString(int)
Output:X = 2310111
mohammed.sikander@cranessoftware.com
34
mohammed.sikander@cranessoftware.com
35
Control Flow - ifIf (boolean)
◦Condition should be of booleanif( x ) invalid is not same as if(x != 0 )
(valid){ {} }boolean x = false;if( x ) if(x = true ) { {} }
mohammed.sikander@cranessoftware.com
36
mohammed.sikander@cranessoftware.com
37
Control Flow - switchThe switch statement is multiway
branch statement. It provides an easy way to dispatch execution to different parts of your code based on the value of an expression.
It often provides a better alternative than a large series of if-else-if statements
Case label can be of◦ Byte, short, char, int ◦ Enum , String (SE 7 & later)◦ Character , Byte, Short,Integer(Wrapper
class)◦ Break is not a must after every case
(similar to C).
mohammed.sikander@cranessoftware.com
38
Control Flow - switchpublic static void main(String [] args){byte b = 1;switch(b){ case 1 : System.out.println("Case 1"); case 2 :System.out.println("Case 2");}}
mohammed.sikander@cranessoftware.com
39
Iteration StatementsWhile Do-whileForEnhanced for loop for accessing
array elements
mohammed.sikander@cranessoftware.com
40
Enhanced for LoopIt was mainly designed for
iteration through collections and arrays. It can be used to make your loops more compact and easy to read.
int [ ] numbers = {5 , 8 , 2, 6,1};For(int x : numbers)
◦S.o.println(x);
mohammed.sikander@cranessoftware.com
41
mohammed.sikander@cranessoftware.com
42
Enhanced For with Multidimensional Arraysint sum = 0;int nums[][] = new int[3][5];for(int i = 0; i < 3; i++)
for(int j=0; j < 5; j++)nums[i][j] = (i+1)*(j+1);
// use for-each for to display and sum the valuesfor(int x[ ] : nums) {
for(int y : x) {System.out.println("Value is: " + y);sum += y;}
}System.out.println("Summation: " + sum);
mohammed.sikander@cranessoftware.com
43
Method 2: No. of columns are same in all rows
Datatype [ ][ ] matrix;Matrix = new datatype[row][col];Method 3 : Each row can have diff. no of
elements(cols)Datatype [ ][ ] matrix;Matrix = new datatype[row][ ];For(I = 0 ; I < row ; i++)
◦ Matrix[i] = new datatype[col]
mohammed.sikander@cranessoftware.com
44
breakUnlabelled break & continue – similar to c/c+
+Labelled breaksearch: for (i = 0; i < arrayOfInts.length; i++) {
for (j = 0; j < arrayOfInts[i].length; j++) { if (arrayOfInts[i][j] == searchfor) { foundIt = true; break search; } }
}
mohammed.sikander@cranessoftware.com
45
mohammed.sikander@cranessoftware.com
46
Kangaroohttps://www.hackerrank.com/challenges/kangaroo
There are two kangaroos on an x-axis ready to jump in the positive direction (i.e, toward positive infinity). The first kangaroo starts at location x1 and moves at a rate of v1 meters per jump. The second kangaroo starts at location x2 and moves at a rate of v2 meters per jump. Given the starting locations and movement rates for each kangaroo, can you determine if they'll ever land at the same location at the same time?
Input Format A single line of four space-separated integers denoting the respective
values of x1, v1, x2, and v2. Output Format Print No if they cannot land on the same location at the same time. Print YES if they can land on the same location at the same time;
also print the location where they will land at same time. Note: The two kangaroos must land at the same location after making the same number
of jumps.
mohammed.sikander@cranessoftware.com
47
mohammed.sikander@cranessoftware.com
48
top related