SlideShare une entreprise Scribd logo
1  sur  53
Java Language Fundamentals




      Java Simplified / Session 2 / 1 of 28
Objectives
  Java Overview
  Interpret the Java Program
  Understand the basics of Java Language
  Identify the Data Types
  Understand arrays
  Identify the Operators
  Format output using Escape Sequence
Overview
 Java is an Object-Oriented Programming (OOP)
  Language
 Can be considered as (((C++)--)++)
 Eliminate unnecessary complexities in C++ like
   Multiple Inheritance
   Pointer
 Better features as oppose to C++
    Platform independence
    Support for the internet
    Security
Features of Java
 Simple
 Object-oriented
 Compiled and interpreted
 Portable
 Distributed
 Secure
Java portablility
Programming Environment
 Command line
   javac hello.java
   java hello
 Integrated Development Environment (IDE)
   Eclipse
   NetBeanIDE
Java Development Kit (JDK)
    Contains the software and tools needed to
     compile, debug and execute applets and
     applications
  A set of command line tools
  Current release: Java 1.6.x
  Freely available at Sun’s official website
 http://www.oracle.com/technetwork/java/javaee/do
 wnloads/index.html


              Java Simplified / Session 1 / 7 of 32
A Sample Java program

// This is a simple program called First.java
class First
{
    public static void main (String [] args)
    {
        System.out.println ("My first program in Java ");
    }
}
Compiling and executing


  The java compiler creates a file called 'First.class'
  that contains the byte codes
 To actually run the program, a java interpreter called java
 is required to execute the code.
Passing Command Line Arguments
 class CommLineArg
 {
  public static void main (String [] pargs)
  {
    System.out.println("These are the arguments passed to
the main method.");
    System.out.println(pargs [0]);
    System.out.println(pargs [1]);
    System.out.println(pargs [2]);
  }
 }
Passing Command Line Arguments
   Output
Basics of the Java Language
                        Data types




     Classes                                Variables

                         Java
                        Basics


            Control
                                     Operators
           Structures
Keywords
abstract     boolean      break     byte           byvalue
case         cast         catch     char           class
const        continue     default   do             double
else         extends      false     final          finally
float        for          future    generic        goto
if           implements   import    inner          Instanceof
null         operator     outer     package        private
protected    Public       rest      return         short
static       Super        switch    synchronized   this
threadsafe   Throw        throws    transient      true
try          Var          void      volatile       while
Primitive Data types
     Data type Size Range
     byte      1       -128-127
     short     2       -32768-32767
     int       4       -2,147,483,648-2,147,483,647
     long      8       -263-263-1
     float     4
     double    8
     boolean   1 bit   true, false
     char      2       Single character
Variables
 Variables must be declared before using,
 Syntax
   datatype identifier [=value][, identifier[=value]...];
 Three components of a declaration are:
    Data type
    Name
    Initial value to be assigned (optional)
Example
 int numberOfStudents;
 String name;
 double x, y;
 boolean isFinished;
 char firstInitial, middleInitial, lastInitial;
Example
class DynVar
{
    public static void main(String [] args)
    {
     double len = 5.0, wide = 7.0;
     double num = Math.sqrt(len * len + wide * wide);
     System.out.println("Value of num after dynamic initialization is " + num);
    }
}



                 Output
Scope and Lifetime of Variables
  Variables can be declared inside a block.
  The block begins with an opening curly brace and
   ends with a closing curly brace.
  A block defines a scope.
  A new scope is created every time a new block is
   created.
  Scope specifies what objects are visible to other
   parts of the program.
  It also determines the life of an object.
Example
class ScopeVar
{
  public static void main(String [] args)
  {
    int num = 10;
    if ( num == 10)
    {
      // num is available in inner scope
      int num1 = num * num;
      System.out.println("Value of num and num1 are " + num + "   " + num1);
    }
    //num1 = 10; ERROR ! num1 is not known
    System.out.println("Value of num is " + num);
  }
}
                Output
Type Casting
  In type casting, a data type is converted into
   another data type.
  Example
      float c = 34.89675f;
      int b = (int)c + 10;
Automatic type and Casting
  There are two type of data conversion: automatic type
   conversion and casting.
  When one type of data is assigned to a variable of
   another type then automatic type conversion takes
   place provided it meets the conditions specified:
     The two types are compatible
     The destination type is larger than the source type.
  Casting is used for explicit type conversion. It loses
   information above the magnitude of the value being
   converted.
Type Promotion Rules
  All byte and short values are promoted to int
   type.
  If one operand is long, the whole expression is
   promoted to long.
  If one operand is float then the whole
   expression is promoted to float.
  If one operand is double then the whole
   expression is promoted to double.
Array Declarations
 Three ways to declare an array are:
   datatype [] identifier;
       int [] anArray;
       anArray = new int[10];
   datatype [] identifier = new datatype[size];
       int [] anArray = new int[10];
   datatype [] identifier = {value1,value2,….valueN};
       int [] anArray = {100,200,300,400,500};
Example – One Dimensional Array
 class ArrDemo
 {
   public static void main(String [] arg)
   {
     double nums[] = {10.1, 11.3, 12.5,13.7, 14.9};
     System.out.println(" The value at location 3 is : " +
 nums[3]);
   }
 }

                           Output
Example – Multi Dimensional Array
 class MultiArrayDemo
 {
    public static void main ( String [] arg)
    {
       int multi[][] = new int [4][];
       multi[0] = new int[1];
       multi[1] = new int[2];
       multi[2] = new int[3];
       multi[3] = new int[4];
       int num = 0;
       for (int count = 0; count < 4; count++)
       {
                    for (int ctr = 0; ctr < count+1; ctr++)
                    {
                                 multi[count][ctr] = num;
                                 num++;
                    }
       }
Operators
  Arithmetic Operators
  Relational Operators
  Logical Operators
  Conditional Operators
  Assignment operators
Arithmetic Operators
  Operands of the arithmetic operators must be of
   numeric type.
  Boolean operands cannot be used, but character
   operands are allowed.
  These operators are used in mathematical
   expressions.
Example
class ArithmeticOp {
   public static void main ( String [] arg) {
    int num = 5, num1 = 12, num2 = 20, result;
    result = num + num1;
    System.out.println("Sum of num and num1 is : (num + num1) " + result);
    result = num % num1;
    System.out.println("Modulus of num and num1 is : (num % num1) " + result);
    result *= num2;
    System.out.println("Product of result and num2 is : (result *= num2) " + result);
   }
}
Relational Operators
  Relational operators test the relation between two
   operands.
  The result of an expression in which relational
   operators are used, is boolean (either true or false).
  Relational operators are used in control structures.
Example
 class RelOp
 {
    public static void main(String [] args)
    {
      float num = 10.0F;
      double num1 = 10.0;
      if (num == num1)
          System.out.println ("num is equal to num1");
      else
            System.out.println ("num is not equal to num1");
    }
 }                      Output
Logical Operators
  Logical operators work with boolean operands.
  Some operators are
    &
    |
    ^
    !
Conditional Operators
 The conditional operator is unique, because it is a ternary or
  triadic operator that has three operands to the expression.
 It can replace certain types of if-then-else statements.
 The code below checks whether a commuter’s age is greater
  than 65 and print the message.
  CommuterCategory = (CommuterAge > 65)? “Senior Citizen” : “Regular”;
Assignment Operators
  The assignment operator is a single equal sign, =,
   and assigns a value to a variable.
  Assigning values to more than one variable can be
   done at a time.
  In other words, it allows us to create a chain of
   assignments.
Operator Precedence
  Parentheses: ( ) and [ ]
  Unary Operators: +, -, ++, --, ~, !
  Arithmetic and Shift operators: *, /, %, +, -, >>, <<
  Relational Operators: >, >=, <, <=, ==, !=
  Logical and Bitwise Operators: &, ^, |, &&, ||,
  Conditional and Assignment Operators:
   ?=, =, *=, /=, +=, -=
  Parentheses are used to change the order in which an
   expression is evaluated. Any part of an expression
   enclosed in parentheses is evaluated first.
Classes in Java
  Class declaration Syntax

     class Classname
     {
            var_datatype variablename;
            :

            met_datatype methodname(parameter_list)
            :
     }
Sample class
Formatting output with Escape Sequences
  Whenever an output is to be displayed on the
   screen, it needs to be formatted.
  The formatting can be done with the help of escape
   sequences that Java provides.
   System.out.println (“Happy tBirthday”);
    Output: Happy Birthday
Control Flow
  All application development environments provide a
   decision making process called control flow
   statements that direct the application execution.
  Flow control enables a developer to create an
   application that can examine the existing
   conditions, and decide a suitable course of action.
  Loops or iteration are an important programming
   construct that can be used to repeatedly execute a set
   of actions.
  Jump statements allow the program to execute in a
   non-linear fashion.
Control Flow Structures in Java
  Decision-making
     if-else statement
     switch-case statement
  Loops
     while loop
     do-while loop
     for loop
if-else statement
  The if-else statement tests the result of a condition, and
   performs appropriate actions based on the result.
  It can be used to route program execution through two different
   paths.
  The format of an if-else statement is very simple and is given
   below:
   if (condition)
   {
        action1;
   }
   else
   {
        action2;
   }
Example
class CheckNum
{
  public static void main(String [] args)
  {
    int num = 10;
    if (num % 2 == 0)
      System.out.println(num + " is an even number");
    else
      System.out.println(num + " is an odd number");
  }
}
switch – case statement
  The switch – case statement can be used in place of
   if-else-if statement.
  It is used in situations where the expression being
   evaluated results in multiple values.
  The use of the switch-case statement leads to
   simpler code, and better performance.
Example
 class SwitchDemo
 {
    public static void main(String[] args)
    {
       int day = 4;
       String str; case 5:
       switch (day) str = "Friday";
       {            case 0:
                       break;
                   case 6:      str = "Sunday";
                       str = "Saturday";
                                break;
                    case 1:
                        break;
                   default:     str = "Monday";
                       str = "Invalid day";
                                break;
                    case 2:
                       }
                   System.out.println(str);
                                str = "Tuesday";
                                                     Output
                   }            break;
                } case 3:
                                str = "Wednesday";
                                break;
                    case 4:
                                str = "Thursday";
                                break;
while Loop
  while loops are used for situations when a loop has to
   be executed as long as certain condition is True.
  The number of times a loop is to be executed is not pre-
   determined, but depends on the condition.
  The syntax is:
      while (condition)
      {
      action statements;
      .
      .
      }
Example
 class FactDemo
 {
   public static void main(String [] args)
   {
     int num = 5, fact = 1;
     while (num >= 1)
     {
            fact *= num;
            num--;
     }
     System.out.println("The factorial of 5 is : " + fact);
   }                     Output
 }
do – while Loop
  The do-while loop executes certain statements till the
   specified condition is True.
  These loops are similar to the while loops, except that a
   do-while loop executes at least once, even if the
   specified condition is False. The syntax is:
      do
      {
        action statements;
      .
      .
      } while (condition);
Example
    class DoWhileDemo
    {
      public static void main(String [] args)
      {
        int count = 1, sum = 0;
        do
        {
               sum += count;
               count++;
        }while (count <= 100);
        System.out.println("The sum of first 100 numbers
 is : " + sum);
      }
    }
      Output
    The sum of first 100 numbers is : 5050
for Loop
 Syntax:
    for (initialization statements; condition; increment / decrement
      statements)
    {
      action statements;
    .
    .
    }
Example
class ForDemo
{
   public static void main(String [] args) {
     int count = 1, sum = 0;
     for (count = 1; count <= 10; count += 2) {
          sum += count;
     }
   System.out.println("The sum of first 5 odd numbers is : " + sum);
   }
}


     Output
   The sum of first 5 odd numbers is : 25
Jump Statements
  Three jump statements are:
     break
     continue
     return
  The three uses of break statements are:
     It terminates a statement sequence in a switch
      statement.
     It can be used to exit a loop.
     It is another form of goto.
Example
    class BrDemoAppl
    {
       public static void main(String [] args)
       {
         for (int count = 1; count <= 100; count++)
 Output  {
 The value if of num 10) : 1
                 (count == is
                  break;
 The value of num is : 2
 The value of num is : 3 value of num is : " + count);
              System.out.println("The
         }
 The value of num is : 4
    System.out.println("The loop is over");
 The value of num is : 5
       }
 The} value of num is : 6
 The   value of num   is : 7
 The   value of num   is : 8
 The   value of num   is : 9
 The   loop is over
Summary
  A Java program consists of a set of classes. A program may contain
     comments. The compiler ignores this commented lines.
    The Java program must have a main() method from where it begins
     its execution.
    Classes define a template for units that store data and code related to
     an entity.
    Variables defined in a class are called the instance variables.
    There are two types of casting:widening and narrowing casting.
    Variables are basic unit of storage.
    Each variable has a scope and lifetime.
    Arrays are used to store several items of same data type in consecutive
     memory locations.
Summary Contd…
  Java provides different types of operators. They include:
     Arithmetic
     Bitwise
     Relational
     Logical
     Conditional
     Assignment
  Java supports the following programming constructs:
     if-else
     switch
     for
     while
     do-while
  The three jump statements-break,continue and return helps to
   transfer control to another part of the program.

Contenu connexe

Tendances (20)

Method overloading
Method overloadingMethod overloading
Method overloading
 
MULTI THREADING IN JAVA
MULTI THREADING IN JAVAMULTI THREADING IN JAVA
MULTI THREADING IN JAVA
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
 
C++ programming
C++ programmingC++ programming
C++ programming
 
Java operators
Java operatorsJava operators
Java operators
 
Core Java Tutorials by Mahika Tutorials
Core Java Tutorials by Mahika TutorialsCore Java Tutorials by Mahika Tutorials
Core Java Tutorials by Mahika Tutorials
 
Super keyword in java
Super keyword in javaSuper keyword in java
Super keyword in java
 
Virtual Functions | Polymorphism | OOP
Virtual Functions | Polymorphism | OOPVirtual Functions | Polymorphism | OOP
Virtual Functions | Polymorphism | OOP
 
C++ Overview PPT
C++ Overview PPTC++ Overview PPT
C++ Overview PPT
 
c++ lab manual
c++ lab manualc++ lab manual
c++ lab manual
 
Operators in java
Operators in javaOperators in java
Operators in java
 
FUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPTFUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPT
 
Control statements in java programmng
Control statements in java programmngControl statements in java programmng
Control statements in java programmng
 
Exception Handling In Java
Exception Handling In JavaException Handling In Java
Exception Handling In Java
 
Java tutorial PPT
Java tutorial PPTJava tutorial PPT
Java tutorial PPT
 
Fundamentals of JAVA
Fundamentals of JAVAFundamentals of JAVA
Fundamentals of JAVA
 
C tutorial
C tutorialC tutorial
C tutorial
 
for loop in java
for loop in java for loop in java
for loop in java
 
Basics of c++ Programming Language
Basics of c++ Programming LanguageBasics of c++ Programming Language
Basics of c++ Programming Language
 
While , For , Do-While Loop
While , For , Do-While LoopWhile , For , Do-While Loop
While , For , Do-While Loop
 

Similaire à Java fundamentals

In this page, we will learn about the basics of OOPs. Object-Oriented Program...
In this page, we will learn about the basics of OOPs. Object-Oriented Program...In this page, we will learn about the basics of OOPs. Object-Oriented Program...
In this page, we will learn about the basics of OOPs. Object-Oriented Program...Indu32
 
Data types and Operators
Data types and OperatorsData types and Operators
Data types and Operatorsraksharao
 
Introduction to Client-Side Javascript
Introduction to Client-Side JavascriptIntroduction to Client-Side Javascript
Introduction to Client-Side JavascriptJulie Iskander
 
Nitin Mishra 0301EC201039 Internship PPT.pptx
Nitin Mishra 0301EC201039 Internship PPT.pptxNitin Mishra 0301EC201039 Internship PPT.pptx
Nitin Mishra 0301EC201039 Internship PPT.pptxshivam460694
 
object oriented programming java lectures
object oriented programming java lecturesobject oriented programming java lectures
object oriented programming java lecturesMSohaib24
 
Learning Java 1 – Introduction
Learning Java 1 – IntroductionLearning Java 1 – Introduction
Learning Java 1 – Introductioncaswenson
 
Java Foundations: Data Types and Type Conversion
Java Foundations: Data Types and Type ConversionJava Foundations: Data Types and Type Conversion
Java Foundations: Data Types and Type ConversionSvetlin Nakov
 
Chapter i(introduction to java)
Chapter i(introduction to java)Chapter i(introduction to java)
Chapter i(introduction to java)Chhom Karath
 
Esoft Metro Campus - Certificate in c / c++ programming
Esoft Metro Campus - Certificate in c / c++ programmingEsoft Metro Campus - Certificate in c / c++ programming
Esoft Metro Campus - Certificate in c / c++ programmingRasan Samarasinghe
 
Computational Problem Solving 016 (1).pptx
Computational Problem Solving 016 (1).pptxComputational Problem Solving 016 (1).pptx
Computational Problem Solving 016 (1).pptx320126552027SURAKATT
 
C programming language tutorial
C programming language tutorial C programming language tutorial
C programming language tutorial javaTpoint s
 

Similaire à Java fundamentals (20)

02basics
02basics02basics
02basics
 
Java tut1
Java tut1Java tut1
Java tut1
 
Tutorial java
Tutorial javaTutorial java
Tutorial java
 
Java Tut1
Java Tut1Java Tut1
Java Tut1
 
Java Tutorial
Java TutorialJava Tutorial
Java Tutorial
 
In this page, we will learn about the basics of OOPs. Object-Oriented Program...
In this page, we will learn about the basics of OOPs. Object-Oriented Program...In this page, we will learn about the basics of OOPs. Object-Oriented Program...
In this page, we will learn about the basics of OOPs. Object-Oriented Program...
 
Data types and Operators
Data types and OperatorsData types and Operators
Data types and Operators
 
Introduction to Client-Side Javascript
Introduction to Client-Side JavascriptIntroduction to Client-Side Javascript
Introduction to Client-Side Javascript
 
Nitin Mishra 0301EC201039 Internship PPT.pptx
Nitin Mishra 0301EC201039 Internship PPT.pptxNitin Mishra 0301EC201039 Internship PPT.pptx
Nitin Mishra 0301EC201039 Internship PPT.pptx
 
Java
JavaJava
Java
 
object oriented programming java lectures
object oriented programming java lecturesobject oriented programming java lectures
object oriented programming java lectures
 
Basic_Java_02.pptx
Basic_Java_02.pptxBasic_Java_02.pptx
Basic_Java_02.pptx
 
Learning Java 1 – Introduction
Learning Java 1 – IntroductionLearning Java 1 – Introduction
Learning Java 1 – Introduction
 
Java Foundations: Data Types and Type Conversion
Java Foundations: Data Types and Type ConversionJava Foundations: Data Types and Type Conversion
Java Foundations: Data Types and Type Conversion
 
Introduction to Java Programming Part 2
Introduction to Java Programming Part 2Introduction to Java Programming Part 2
Introduction to Java Programming Part 2
 
Java q ref 2018
Java q ref 2018Java q ref 2018
Java q ref 2018
 
Chapter i(introduction to java)
Chapter i(introduction to java)Chapter i(introduction to java)
Chapter i(introduction to java)
 
Esoft Metro Campus - Certificate in c / c++ programming
Esoft Metro Campus - Certificate in c / c++ programmingEsoft Metro Campus - Certificate in c / c++ programming
Esoft Metro Campus - Certificate in c / c++ programming
 
Computational Problem Solving 016 (1).pptx
Computational Problem Solving 016 (1).pptxComputational Problem Solving 016 (1).pptx
Computational Problem Solving 016 (1).pptx
 
C programming language tutorial
C programming language tutorial C programming language tutorial
C programming language tutorial
 

Dernier

Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Zilliz
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024The Digital Insurer
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Jeffrey Haguewood
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfOverkill Security
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Orbitshub
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdfSandro Moreira
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 

Dernier (20)

Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 

Java fundamentals

  • 1. Java Language Fundamentals Java Simplified / Session 2 / 1 of 28
  • 2. Objectives  Java Overview  Interpret the Java Program  Understand the basics of Java Language  Identify the Data Types  Understand arrays  Identify the Operators  Format output using Escape Sequence
  • 3. Overview  Java is an Object-Oriented Programming (OOP) Language  Can be considered as (((C++)--)++)  Eliminate unnecessary complexities in C++ like  Multiple Inheritance  Pointer  Better features as oppose to C++  Platform independence  Support for the internet  Security
  • 4. Features of Java  Simple  Object-oriented  Compiled and interpreted  Portable  Distributed  Secure
  • 6. Programming Environment  Command line javac hello.java java hello  Integrated Development Environment (IDE) Eclipse NetBeanIDE
  • 7. Java Development Kit (JDK)  Contains the software and tools needed to compile, debug and execute applets and applications  A set of command line tools  Current release: Java 1.6.x  Freely available at Sun’s official website http://www.oracle.com/technetwork/java/javaee/do wnloads/index.html Java Simplified / Session 1 / 7 of 32
  • 8. A Sample Java program // This is a simple program called First.java class First { public static void main (String [] args) { System.out.println ("My first program in Java "); } }
  • 9. Compiling and executing The java compiler creates a file called 'First.class' that contains the byte codes To actually run the program, a java interpreter called java is required to execute the code.
  • 10. Passing Command Line Arguments class CommLineArg { public static void main (String [] pargs) { System.out.println("These are the arguments passed to the main method."); System.out.println(pargs [0]); System.out.println(pargs [1]); System.out.println(pargs [2]); } }
  • 11. Passing Command Line Arguments Output
  • 12. Basics of the Java Language Data types Classes Variables Java Basics Control Operators Structures
  • 13. Keywords abstract boolean break byte byvalue case cast catch char class const continue default do double else extends false final finally float for future generic goto if implements import inner Instanceof null operator outer package private protected Public rest return short static Super switch synchronized this threadsafe Throw throws transient true try Var void volatile while
  • 14. Primitive Data types Data type Size Range byte 1 -128-127 short 2 -32768-32767 int 4 -2,147,483,648-2,147,483,647 long 8 -263-263-1 float 4 double 8 boolean 1 bit true, false char 2 Single character
  • 15. Variables  Variables must be declared before using,  Syntax datatype identifier [=value][, identifier[=value]...];  Three components of a declaration are:  Data type  Name  Initial value to be assigned (optional)
  • 16. Example int numberOfStudents; String name; double x, y; boolean isFinished; char firstInitial, middleInitial, lastInitial;
  • 17. Example class DynVar { public static void main(String [] args) { double len = 5.0, wide = 7.0; double num = Math.sqrt(len * len + wide * wide); System.out.println("Value of num after dynamic initialization is " + num); } } Output
  • 18. Scope and Lifetime of Variables  Variables can be declared inside a block.  The block begins with an opening curly brace and ends with a closing curly brace.  A block defines a scope.  A new scope is created every time a new block is created.  Scope specifies what objects are visible to other parts of the program.  It also determines the life of an object.
  • 19. Example class ScopeVar { public static void main(String [] args) { int num = 10; if ( num == 10) { // num is available in inner scope int num1 = num * num; System.out.println("Value of num and num1 are " + num + " " + num1); } //num1 = 10; ERROR ! num1 is not known System.out.println("Value of num is " + num); } } Output
  • 20. Type Casting  In type casting, a data type is converted into another data type.  Example float c = 34.89675f; int b = (int)c + 10;
  • 21. Automatic type and Casting  There are two type of data conversion: automatic type conversion and casting.  When one type of data is assigned to a variable of another type then automatic type conversion takes place provided it meets the conditions specified:  The two types are compatible  The destination type is larger than the source type.  Casting is used for explicit type conversion. It loses information above the magnitude of the value being converted.
  • 22. Type Promotion Rules  All byte and short values are promoted to int type.  If one operand is long, the whole expression is promoted to long.  If one operand is float then the whole expression is promoted to float.  If one operand is double then the whole expression is promoted to double.
  • 23. Array Declarations  Three ways to declare an array are: datatype [] identifier; int [] anArray; anArray = new int[10]; datatype [] identifier = new datatype[size]; int [] anArray = new int[10]; datatype [] identifier = {value1,value2,….valueN}; int [] anArray = {100,200,300,400,500};
  • 24. Example – One Dimensional Array class ArrDemo { public static void main(String [] arg) { double nums[] = {10.1, 11.3, 12.5,13.7, 14.9}; System.out.println(" The value at location 3 is : " + nums[3]); } } Output
  • 25. Example – Multi Dimensional Array class MultiArrayDemo { public static void main ( String [] arg) { int multi[][] = new int [4][]; multi[0] = new int[1]; multi[1] = new int[2]; multi[2] = new int[3]; multi[3] = new int[4]; int num = 0; for (int count = 0; count < 4; count++) { for (int ctr = 0; ctr < count+1; ctr++) { multi[count][ctr] = num; num++; } }
  • 26. Operators  Arithmetic Operators  Relational Operators  Logical Operators  Conditional Operators  Assignment operators
  • 27. Arithmetic Operators  Operands of the arithmetic operators must be of numeric type.  Boolean operands cannot be used, but character operands are allowed.  These operators are used in mathematical expressions.
  • 28. Example class ArithmeticOp { public static void main ( String [] arg) { int num = 5, num1 = 12, num2 = 20, result; result = num + num1; System.out.println("Sum of num and num1 is : (num + num1) " + result); result = num % num1; System.out.println("Modulus of num and num1 is : (num % num1) " + result); result *= num2; System.out.println("Product of result and num2 is : (result *= num2) " + result); } }
  • 29. Relational Operators  Relational operators test the relation between two operands.  The result of an expression in which relational operators are used, is boolean (either true or false).  Relational operators are used in control structures.
  • 30. Example class RelOp { public static void main(String [] args) { float num = 10.0F; double num1 = 10.0; if (num == num1) System.out.println ("num is equal to num1"); else System.out.println ("num is not equal to num1"); } } Output
  • 31. Logical Operators  Logical operators work with boolean operands.  Some operators are & | ^ !
  • 32. Conditional Operators  The conditional operator is unique, because it is a ternary or triadic operator that has three operands to the expression.  It can replace certain types of if-then-else statements.  The code below checks whether a commuter’s age is greater than 65 and print the message. CommuterCategory = (CommuterAge > 65)? “Senior Citizen” : “Regular”;
  • 33. Assignment Operators  The assignment operator is a single equal sign, =, and assigns a value to a variable.  Assigning values to more than one variable can be done at a time.  In other words, it allows us to create a chain of assignments.
  • 34. Operator Precedence  Parentheses: ( ) and [ ]  Unary Operators: +, -, ++, --, ~, !  Arithmetic and Shift operators: *, /, %, +, -, >>, <<  Relational Operators: >, >=, <, <=, ==, !=  Logical and Bitwise Operators: &, ^, |, &&, ||,  Conditional and Assignment Operators: ?=, =, *=, /=, +=, -=  Parentheses are used to change the order in which an expression is evaluated. Any part of an expression enclosed in parentheses is evaluated first.
  • 35. Classes in Java  Class declaration Syntax class Classname { var_datatype variablename; : met_datatype methodname(parameter_list) : }
  • 37. Formatting output with Escape Sequences  Whenever an output is to be displayed on the screen, it needs to be formatted.  The formatting can be done with the help of escape sequences that Java provides. System.out.println (“Happy tBirthday”);  Output: Happy Birthday
  • 38. Control Flow  All application development environments provide a decision making process called control flow statements that direct the application execution.  Flow control enables a developer to create an application that can examine the existing conditions, and decide a suitable course of action.  Loops or iteration are an important programming construct that can be used to repeatedly execute a set of actions.  Jump statements allow the program to execute in a non-linear fashion.
  • 39. Control Flow Structures in Java  Decision-making  if-else statement  switch-case statement  Loops  while loop  do-while loop  for loop
  • 40. if-else statement  The if-else statement tests the result of a condition, and performs appropriate actions based on the result.  It can be used to route program execution through two different paths.  The format of an if-else statement is very simple and is given below: if (condition) { action1; } else { action2; }
  • 41. Example class CheckNum { public static void main(String [] args) { int num = 10; if (num % 2 == 0) System.out.println(num + " is an even number"); else System.out.println(num + " is an odd number"); } }
  • 42. switch – case statement  The switch – case statement can be used in place of if-else-if statement.  It is used in situations where the expression being evaluated results in multiple values.  The use of the switch-case statement leads to simpler code, and better performance.
  • 43. Example class SwitchDemo { public static void main(String[] args) { int day = 4; String str; case 5: switch (day) str = "Friday"; { case 0: break; case 6: str = "Sunday"; str = "Saturday"; break; case 1: break; default: str = "Monday"; str = "Invalid day"; break; case 2: } System.out.println(str); str = "Tuesday"; Output } break; } case 3: str = "Wednesday"; break; case 4: str = "Thursday"; break;
  • 44. while Loop  while loops are used for situations when a loop has to be executed as long as certain condition is True.  The number of times a loop is to be executed is not pre- determined, but depends on the condition.  The syntax is: while (condition) { action statements; . . }
  • 45. Example class FactDemo { public static void main(String [] args) { int num = 5, fact = 1; while (num >= 1) { fact *= num; num--; } System.out.println("The factorial of 5 is : " + fact); } Output }
  • 46. do – while Loop  The do-while loop executes certain statements till the specified condition is True.  These loops are similar to the while loops, except that a do-while loop executes at least once, even if the specified condition is False. The syntax is: do { action statements; . . } while (condition);
  • 47. Example class DoWhileDemo { public static void main(String [] args) { int count = 1, sum = 0; do { sum += count; count++; }while (count <= 100); System.out.println("The sum of first 100 numbers is : " + sum); } } Output The sum of first 100 numbers is : 5050
  • 48. for Loop Syntax: for (initialization statements; condition; increment / decrement statements) { action statements; . . }
  • 49. Example class ForDemo { public static void main(String [] args) { int count = 1, sum = 0; for (count = 1; count <= 10; count += 2) { sum += count; } System.out.println("The sum of first 5 odd numbers is : " + sum); } } Output The sum of first 5 odd numbers is : 25
  • 50. Jump Statements  Three jump statements are:  break  continue  return  The three uses of break statements are:  It terminates a statement sequence in a switch statement.  It can be used to exit a loop.  It is another form of goto.
  • 51. Example class BrDemoAppl { public static void main(String [] args) { for (int count = 1; count <= 100; count++) Output { The value if of num 10) : 1 (count == is break; The value of num is : 2 The value of num is : 3 value of num is : " + count); System.out.println("The } The value of num is : 4 System.out.println("The loop is over"); The value of num is : 5 } The} value of num is : 6 The value of num is : 7 The value of num is : 8 The value of num is : 9 The loop is over
  • 52. Summary  A Java program consists of a set of classes. A program may contain comments. The compiler ignores this commented lines.  The Java program must have a main() method from where it begins its execution.  Classes define a template for units that store data and code related to an entity.  Variables defined in a class are called the instance variables.  There are two types of casting:widening and narrowing casting.  Variables are basic unit of storage.  Each variable has a scope and lifetime.  Arrays are used to store several items of same data type in consecutive memory locations.
  • 53. Summary Contd…  Java provides different types of operators. They include:  Arithmetic  Bitwise  Relational  Logical  Conditional  Assignment  Java supports the following programming constructs:  if-else  switch  for  while  do-while  The three jump statements-break,continue and return helps to transfer control to another part of the program.