SlideShare una empresa de Scribd logo
1 de 48
Java - Basics
Prepared by
Mohammed Sikander
Technical Lead
Cranes Varsity
Language Basics
Variables
Operators
Control-flow
Arrays
Converting Ideas to Program
mohammed.sikander@cranessoftware.
com 3
C++ Compilation Process
mohammed.sikander@cranessoftware.
com 4
JAVA Compilation Process
mohammed.sikander@cranessoftware.
com 5
First Java Program
mohammed.sikander@cranessoftware.
com 6
 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 7
mohammed.sikander@cranessoftware.
com 8
 If class is public, filename should
match class name.
 If class is not public, filename can be
different.
mohammed.sikander@cranessoftware.
com 9
 javac
FirstProgram.java
 Java
SecondProgram
mohammed.sikander@cranessoftware.
com 10
Naming Conventions
Name Convention
class Names hould start with uppercase letter and be a
noun
e.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 11
CamelCase in java naming
conventions
 Java 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 12
Variables naming - Rules
 All 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: NO
Grade Grade(Test)
GradeOnTest GradeTest#1
Grade_On_Test 3rd_Test_Grade
GradeTest Grade Test (has a space)
int $a = 5;
int a$b = 8;
int _x = 4;
int _ = 9;
mohammed.sikander@cranessoftware.
com 13
Variable naming – Guidelines
 The 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 14
mohammed.sikander@cranessoftware.
com 15
Datatypes
 Byte - 1 byte
 Short - 2 byte
 Int - 4
 Long - 8
 Float - 4 (IEEE 754)
 Double - 8 (IEEE 754)
 Char - 2 (unicode)
 Boolean - 1 (size undefined)
 Note : java does not support unsigned.
mohammed.sikander@cranessoftware.
com 16
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.23e2
 Float 4.5f 1.23e2f
mohammed.sikander@cranessoftware.
com 17
Write the Output
class ArithmeticOperation {
public static void main(String [] args )
{
byte a = 5;
byte b = 10;
byte sum = a + b;
System.out.println("Sum = " +
sum);
}
}mohammed.sikander@cranessoftware.
com 18
int sum = a + b;
byte sum = (byte)(a +
b);
Write the Output
Java Program
class ArithmeticOperation {
public static void main(String [] args ) {
float res = 9 % 2.5f;
System.out.println("res = " + res);
}
}
mohammed.sikander@cranessoftware.
com 19
C/ C++ Program
int main( )
{
float res = 9 % 2.5f;
printf(" %f " ,res);
}
Arithmetic Operators
 int / int => int
 float / int => float
 byte + byte => int
 % operator can be applied to float-
types
 Eg : 5.0 % 2.4 = 0.2
 9 % 2.5 => 1.5; 10 % 2.5 => 0
mohammed.sikander@cranessoftware.
com 20
Output
class 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 21
Conversion from Small to
Large
public 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 22
Conversion from Large to
Small
public 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 23
Write the Output
public class ByteDemo {
public static void main(String [] args)
{
byte x = 127;
System.out.println(x);
x++;
System.out.println(x);
}
}
mohammed.sikander@cranessoftware.
com 24
Code to Print ASCII / UNICODE
Value of a Character
mohammed.sikander@cranessoftware.
com 25
public class CharAsciiValue {
public static void main(String[] args)
{
char a = 'A';
System.out.println(a + " " + (int)a);
}
}
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 26
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 27
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
");
else
System.out.print(“FALS
E");
}
mohammed.sikander@cranessoftware.
com 28
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 29
Logical Operators
 && , || - Short-circuiting operators, Same as
C
 & , | - evaluates both condition.
mohammed.sikander@cranessoftware.
com 30
if(++x > 5 & ++ y > 5)
{
}
Both x and y are updated
if(++x > 5 && ++ y > 5)
{
}
Only x is updated.
Write the Output
mohammed.sikander@cranessoftware.
com 31
Try with following Changes
1. Change the value of x to 8.
2. Replace && with &
3. Try with OR Operators (| | and | )
Bitwise Operators
 Can 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 32
 To print in Binary Form
 Integer.toBinaryString(int)
mohammed.sikander@cranessoftware.
com 33
Output:
X = 23
10111
mohammed.sikander@cranessoftware.
com 34
Control Flow - if
 If (boolean)
◦ Condition should be of boolean
if( x ) invalid is not same as if(x != 0 ) (valid)
{ {
} }
boolean x = false;
if( x ) if(x = true )
{ {
} }
mohammed.sikander@cranessoftware.
com 35
mohammed.sikander@cranessoftware.
com 36
Control Flow - switch
 The 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 37
Control Flow - switch
public 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 38
Iteration Statements
 While
 Do-while
 For
 Enhanced for loop for accessing array
elements
mohammed.sikander@cranessoftware.
com 39
Enhanced for Loop
 It 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 40
mohammed.sikander@cranessoftware.
com 41
Enhanced For with
Multidimensional Arrays
int 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 values
for(int x[ ] : nums) {
for(int y : x) {
System.out.println("Value is: " + y);
sum += y;
}
}
System.out.println("Summation: " + sum);
mohammed.sikander@cranessoftware.
com 42
 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 43
break
 Unlabelled break & continue – similar to c/c++
 Labelled break
search:
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 44
mohammed.sikander@cranessoftware.
com 45
Kangaroo
https://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 46
mohammed.sikander@cranessoftware.
com 47
mohammed.sikander@cranessoftware.
com 48

Más contenido relacionado

La actualidad más candente (20)

Arrays in C
Arrays in CArrays in C
Arrays in C
 
Java Arrays
Java ArraysJava Arrays
Java Arrays
 
C# Arrays
C# ArraysC# Arrays
C# Arrays
 
Multi dimensional array
Multi dimensional arrayMulti dimensional array
Multi dimensional array
 
Arrays C#
Arrays C#Arrays C#
Arrays C#
 
Arrays in Java | Edureka
Arrays in Java | EdurekaArrays in Java | Edureka
Arrays in Java | Edureka
 
Array lecture
Array lectureArray lecture
Array lecture
 
Array in Java
Array in JavaArray in Java
Array in Java
 
array
array array
array
 
C arrays
C arraysC arrays
C arrays
 
Array Introduction One-dimensional array Multidimensional array
Array Introduction One-dimensional array Multidimensional arrayArray Introduction One-dimensional array Multidimensional array
Array Introduction One-dimensional array Multidimensional array
 
2D Array
2D Array 2D Array
2D Array
 
Chapter 6 arrays part-1
Chapter 6   arrays part-1Chapter 6   arrays part-1
Chapter 6 arrays part-1
 
Array&amp;string
Array&amp;stringArray&amp;string
Array&amp;string
 
Array
ArrayArray
Array
 
Two dimensional array
Two dimensional arrayTwo dimensional array
Two dimensional array
 
Java Foundations: Lists, ArrayList<T>
Java Foundations: Lists, ArrayList<T>Java Foundations: Lists, ArrayList<T>
Java Foundations: Lists, ArrayList<T>
 
18. Java associative arrays
18. Java associative arrays18. Java associative arrays
18. Java associative arrays
 
Java Foundations: Arrays
Java Foundations: ArraysJava Foundations: Arrays
Java Foundations: Arrays
 
Lec 25 - arrays-strings
Lec 25 - arrays-stringsLec 25 - arrays-strings
Lec 25 - arrays-strings
 

Destacado (20)

Keywords of java
Keywords of javaKeywords of java
Keywords of java
 
L2 datatypes and variables
L2 datatypes and variablesL2 datatypes and variables
L2 datatypes and variables
 
Yaazli International Spring Training
Yaazli International Spring Training Yaazli International Spring Training
Yaazli International Spring Training
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
 
02basics
02basics02basics
02basics
 
Java quick reference v2
Java quick reference v2Java quick reference v2
Java quick reference v2
 
09events
09events09events
09events
 
Yaazli International Hibernate Training
Yaazli International Hibernate TrainingYaazli International Hibernate Training
Yaazli International Hibernate Training
 
Toolbarexample
ToolbarexampleToolbarexample
Toolbarexample
 
Savr
SavrSavr
Savr
 
Yaazli International Web Project Workshop
Yaazli International Web Project WorkshopYaazli International Web Project Workshop
Yaazli International Web Project Workshop
 
Non ieee dot net projects list
Non  ieee dot net projects list Non  ieee dot net projects list
Non ieee dot net projects list
 
For Loops and Variables in Java
For Loops and Variables in JavaFor Loops and Variables in Java
For Loops and Variables in Java
 
Yaazli International AngularJS 5 Training
Yaazli International AngularJS 5 TrainingYaazli International AngularJS 5 Training
Yaazli International AngularJS 5 Training
 
Core java online training
Core java online trainingCore java online training
Core java online training
 
Exception handling in java
Exception handling in java Exception handling in java
Exception handling in java
 
Singleton pattern
Singleton patternSingleton pattern
Singleton pattern
 
DIWE - Using Extensions and Image Manipulation
DIWE - Using Extensions and Image ManipulationDIWE - Using Extensions and Image Manipulation
DIWE - Using Extensions and Image Manipulation
 
Non ieee java projects list
Non  ieee java projects list Non  ieee java projects list
Non ieee java projects list
 
Java Basic Operators
Java Basic OperatorsJava Basic Operators
Java Basic Operators
 

Similar a Java notes 1 - operators control-flow

The Java Fx Platform – A Java Developer’S Guide
The Java Fx Platform – A Java Developer’S GuideThe Java Fx Platform – A Java Developer’S Guide
The Java Fx Platform – A Java Developer’S GuideStephen Chin
 
20.1 Java working with abstraction
20.1 Java working with abstraction20.1 Java working with abstraction
20.1 Java working with abstractionIntro C# Book
 
Java 5 6 Generics, Concurrency, Garbage Collection, Tuning
Java 5 6 Generics, Concurrency, Garbage Collection, TuningJava 5 6 Generics, Concurrency, Garbage Collection, Tuning
Java 5 6 Generics, Concurrency, Garbage Collection, TuningCarol McDonald
 
Chapter i(introduction to java)
Chapter i(introduction to java)Chapter i(introduction to java)
Chapter i(introduction to java)Chhom Karath
 
Automatically Documenting Program Changes
Automatically Documenting Program ChangesAutomatically Documenting Program Changes
Automatically Documenting Program ChangesRay Buse
 
How do you create a programming language for the JVM?
How do you create a programming language for the JVM?How do you create a programming language for the JVM?
How do you create a programming language for the JVM?Federico Tomassetti
 
Keynote (Mike Muller) - Is There Anything New in Heterogeneous Computing - by...
Keynote (Mike Muller) - Is There Anything New in Heterogeneous Computing - by...Keynote (Mike Muller) - Is There Anything New in Heterogeneous Computing - by...
Keynote (Mike Muller) - Is There Anything New in Heterogeneous Computing - by...AMD Developer Central
 
Class 12 computer sample paper with answers
Class 12 computer sample paper with answersClass 12 computer sample paper with answers
Class 12 computer sample paper with answersdebarghyamukherjee60
 
C multiple choice questions and answers pdf
C multiple choice questions and answers pdfC multiple choice questions and answers pdf
C multiple choice questions and answers pdfchoconyeuquy
 
elm-d3 @ NYC D3.js Meetup (30 June, 2014)
elm-d3 @ NYC D3.js Meetup (30 June, 2014)elm-d3 @ NYC D3.js Meetup (30 June, 2014)
elm-d3 @ NYC D3.js Meetup (30 June, 2014)Spiros
 
Addressing Scenario
Addressing ScenarioAddressing Scenario
Addressing ScenarioTara Hardin
 
Java concepts and questions
Java concepts and questionsJava concepts and questions
Java concepts and questionsFarag Zakaria
 
CSE215_Module_02_Elementary_Programming.ppt
CSE215_Module_02_Elementary_Programming.pptCSE215_Module_02_Elementary_Programming.ppt
CSE215_Module_02_Elementary_Programming.pptRashedurRahman18
 
Object oriented programming system with C++
Object oriented programming system with C++Object oriented programming system with C++
Object oriented programming system with C++msharshitha03s
 

Similar a Java notes 1 - operators control-flow (20)

The Java Fx Platform – A Java Developer’S Guide
The Java Fx Platform – A Java Developer’S GuideThe Java Fx Platform – A Java Developer’S Guide
The Java Fx Platform – A Java Developer’S Guide
 
00_Introduction to Java.ppt
00_Introduction to Java.ppt00_Introduction to Java.ppt
00_Introduction to Java.ppt
 
Nalinee java
Nalinee javaNalinee java
Nalinee java
 
20.1 Java working with abstraction
20.1 Java working with abstraction20.1 Java working with abstraction
20.1 Java working with abstraction
 
C++ tutorials
C++ tutorialsC++ tutorials
C++ tutorials
 
Java 5 6 Generics, Concurrency, Garbage Collection, Tuning
Java 5 6 Generics, Concurrency, Garbage Collection, TuningJava 5 6 Generics, Concurrency, Garbage Collection, Tuning
Java 5 6 Generics, Concurrency, Garbage Collection, Tuning
 
Chapter i(introduction to java)
Chapter i(introduction to java)Chapter i(introduction to java)
Chapter i(introduction to java)
 
Automatically Documenting Program Changes
Automatically Documenting Program ChangesAutomatically Documenting Program Changes
Automatically Documenting Program Changes
 
How do you create a programming language for the JVM?
How do you create a programming language for the JVM?How do you create a programming language for the JVM?
How do you create a programming language for the JVM?
 
Keynote (Mike Muller) - Is There Anything New in Heterogeneous Computing - by...
Keynote (Mike Muller) - Is There Anything New in Heterogeneous Computing - by...Keynote (Mike Muller) - Is There Anything New in Heterogeneous Computing - by...
Keynote (Mike Muller) - Is There Anything New in Heterogeneous Computing - by...
 
C language
C languageC language
C language
 
Clojure And Swing
Clojure And SwingClojure And Swing
Clojure And Swing
 
Class 12 computer sample paper with answers
Class 12 computer sample paper with answersClass 12 computer sample paper with answers
Class 12 computer sample paper with answers
 
C multiple choice questions and answers pdf
C multiple choice questions and answers pdfC multiple choice questions and answers pdf
C multiple choice questions and answers pdf
 
elm-d3 @ NYC D3.js Meetup (30 June, 2014)
elm-d3 @ NYC D3.js Meetup (30 June, 2014)elm-d3 @ NYC D3.js Meetup (30 June, 2014)
elm-d3 @ NYC D3.js Meetup (30 June, 2014)
 
Addressing Scenario
Addressing ScenarioAddressing Scenario
Addressing Scenario
 
Java concepts and questions
Java concepts and questionsJava concepts and questions
Java concepts and questions
 
Core java day1
Core java day1Core java day1
Core java day1
 
CSE215_Module_02_Elementary_Programming.ppt
CSE215_Module_02_Elementary_Programming.pptCSE215_Module_02_Elementary_Programming.ppt
CSE215_Module_02_Elementary_Programming.ppt
 
Object oriented programming system with C++
Object oriented programming system with C++Object oriented programming system with C++
Object oriented programming system with C++
 

Más de Mohammed Sikander (20)

Operator Overloading in C++
Operator Overloading in C++Operator Overloading in C++
Operator Overloading in C++
 
Python_Regular Expression
Python_Regular ExpressionPython_Regular Expression
Python_Regular Expression
 
Modern_CPP-Range-Based For Loop.pptx
Modern_CPP-Range-Based For Loop.pptxModern_CPP-Range-Based For Loop.pptx
Modern_CPP-Range-Based For Loop.pptx
 
Modern_cpp_auto.pdf
Modern_cpp_auto.pdfModern_cpp_auto.pdf
Modern_cpp_auto.pdf
 
Python Functions
Python   FunctionsPython   Functions
Python Functions
 
Python dictionary
Python   dictionaryPython   dictionary
Python dictionary
 
Python exception handling
Python   exception handlingPython   exception handling
Python exception handling
 
Python tuple
Python   tuplePython   tuple
Python tuple
 
Python strings
Python stringsPython strings
Python strings
 
Python set
Python setPython set
Python set
 
Python list
Python listPython list
Python list
 
Python Flow Control
Python Flow ControlPython Flow Control
Python Flow Control
 
Introduction to Python
Introduction to Python  Introduction to Python
Introduction to Python
 
Pointer basics
Pointer basicsPointer basics
Pointer basics
 
Signal
SignalSignal
Signal
 
File management
File managementFile management
File management
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
 
CPP Language Basics - Reference
CPP Language Basics - ReferenceCPP Language Basics - Reference
CPP Language Basics - Reference
 
Java strings
Java   stringsJava   strings
Java strings
 
Questions typedef and macros
Questions typedef and macrosQuestions typedef and macros
Questions typedef and macros
 

Último

Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmSujith Sukumaran
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odishasmiwainfosol
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanyChristoph Pohl
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationBradBedford3
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...Technogeeks
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
Buds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in NoidaBuds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in Noidabntitsolutionsrishis
 
How to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfHow to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfLivetecs LLC
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024StefanoLambiase
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Matt Ray
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commercemanigoyal112
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Hr365.us smith
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...confluent
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Natan Silnitsky
 
Best Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdfBest Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdfIdiosysTechnologies1
 

Último (20)

Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalm
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion Application
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...
 
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort ServiceHot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
Buds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in NoidaBuds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in Noida
 
How to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfHow to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdf
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commerce
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
 
Best Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdfBest Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdf
 
Advantages of Odoo ERP 17 for Your Business
Advantages of Odoo ERP 17 for Your BusinessAdvantages of Odoo ERP 17 for Your Business
Advantages of Odoo ERP 17 for Your Business
 

Java notes 1 - operators control-flow

  • 1. Java - Basics Prepared by Mohammed Sikander Technical Lead Cranes Varsity
  • 3. Converting Ideas to Program mohammed.sikander@cranessoftware. com 3
  • 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 7
  • 9.  If class is public, filename should match class name.  If class is not public, filename can be different. mohammed.sikander@cranessoftware. com 9
  • 11. Naming Conventions Name Convention class Names hould start with uppercase letter and be a noun e.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 11
  • 12. CamelCase in java naming conventions  Java 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 12
  • 13. Variables naming - Rules  All 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: NO Grade Grade(Test) GradeOnTest GradeTest#1 Grade_On_Test 3rd_Test_Grade GradeTest Grade Test (has a space) int $a = 5; int a$b = 8; int _x = 4; int _ = 9; mohammed.sikander@cranessoftware. com 13
  • 14. Variable naming – Guidelines  The 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 14
  • 16. Datatypes  Byte - 1 byte  Short - 2 byte  Int - 4  Long - 8  Float - 4 (IEEE 754)  Double - 8 (IEEE 754)  Char - 2 (unicode)  Boolean - 1 (size undefined)  Note : java does not support unsigned. mohammed.sikander@cranessoftware. com 16
  • 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.23e2  Float 4.5f 1.23e2f mohammed.sikander@cranessoftware. com 17
  • 18. Write the Output class ArithmeticOperation { public static void main(String [] args ) { byte a = 5; byte b = 10; byte sum = a + b; System.out.println("Sum = " + sum); } }mohammed.sikander@cranessoftware. com 18 int sum = a + b; byte sum = (byte)(a + b);
  • 19. Write the Output Java Program class ArithmeticOperation { public static void main(String [] args ) { float res = 9 % 2.5f; System.out.println("res = " + res); } } mohammed.sikander@cranessoftware. com 19 C/ C++ Program int main( ) { float res = 9 % 2.5f; printf(" %f " ,res); }
  • 20. Arithmetic Operators  int / int => int  float / int => float  byte + byte => int  % operator can be applied to float- types  Eg : 5.0 % 2.4 = 0.2  9 % 2.5 => 1.5; 10 % 2.5 => 0 mohammed.sikander@cranessoftware. com 20
  • 21. Output class 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 21
  • 22. Conversion from Small to Large public 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 22
  • 23. Conversion from Large to Small public 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 23
  • 24. Write the Output public class ByteDemo { public static void main(String [] args) { byte x = 127; System.out.println(x); x++; System.out.println(x); } } mohammed.sikander@cranessoftware. com 24
  • 25. Code to Print ASCII / UNICODE Value of a Character mohammed.sikander@cranessoftware. com 25 public class CharAsciiValue { public static void main(String[] args) { char a = 'A'; System.out.println(a + " " + (int)a); } }
  • 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 26
  • 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 27
  • 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 "); else System.out.print(“FALS E"); } mohammed.sikander@cranessoftware. com 28
  • 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 29
  • 30. Logical Operators  && , || - Short-circuiting operators, Same as C  & , | - evaluates both condition. mohammed.sikander@cranessoftware. com 30 if(++x > 5 & ++ y > 5) { } Both x and y are updated if(++x > 5 && ++ y > 5) { } Only x is updated.
  • 31. Write the Output mohammed.sikander@cranessoftware. com 31 Try with following Changes 1. Change the value of x to 8. 2. Replace && with & 3. Try with OR Operators (| | and | )
  • 32. Bitwise Operators  Can 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 32
  • 33.  To print in Binary Form  Integer.toBinaryString(int) mohammed.sikander@cranessoftware. com 33 Output: X = 23 10111
  • 35. Control Flow - if  If (boolean) ◦ Condition should be of boolean if( x ) invalid is not same as if(x != 0 ) (valid) { { } } boolean x = false; if( x ) if(x = true ) { { } } mohammed.sikander@cranessoftware. com 35
  • 37. Control Flow - switch  The 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 37
  • 38. Control Flow - switch public 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 38
  • 39. Iteration Statements  While  Do-while  For  Enhanced for loop for accessing array elements mohammed.sikander@cranessoftware. com 39
  • 40. Enhanced for Loop  It 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 40
  • 42. Enhanced For with Multidimensional Arrays int 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 values for(int x[ ] : nums) { for(int y : x) { System.out.println("Value is: " + y); sum += y; } } System.out.println("Summation: " + sum); mohammed.sikander@cranessoftware. com 42
  • 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 43
  • 44. break  Unlabelled break & continue – similar to c/c++  Labelled break search: 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 44
  • 46. Kangaroo https://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 46

Notas del editor

  1. public class FirstProgram { /** * @param args */ public static void main(String[] args) { System.out.println("My First Java Program"); } }
  2. How can we verify the size. Ans : By checking the range of values
  3. In Java SE 7 and later, any number of underscore characters (_) can appear anywhere between digits in a numerical literal. This feature enables you, for example. to separate groups of digits in numeric literals, which can improve the readability of your code. long creditCardNumber = 1234_5678_9012_3456L; long hexBytes = 0xFF_EC_DE_5E; long hexWords = 0xCAFE_BABE; byte nybbles = 0b0010_0101; long bytes = 0b11010010_01101001_10010100_10010010; You can place underscores only between digits; you cannot place underscores in the following places: At the beginning or end of a number Adjacent to a decimal point in a floating point literal Prior to an F or L suffix In positions where a string of digits is expected
  4. 10.0+2.0/(3.0−2.0*2.0);
  5. If(x) – x is integer If(x != 0) result is boolean. boolean  flag = false; if(flag)  //Valid in Java {                }    if(flag = true)     //valid  {                }     int x = 5;   if(x = 0) //Invalid in Java   {   }
  6. public static void main(String[] args) { int a = 5; int b = 10; boolean res = a > b; if(res) System.out.println(a); else System.out.println(b); }