SlideShare una empresa de Scribd logo
1 de 52
Java Session 4
Contents…
Data Types
Type Conversion and Casting
Variables
Scope and lifetime of variables
Operators
Expressions
Control Statements
DATA TYPES
• Variables are nothing but reserved memory
  locations to store values. This means that
  when you create a variable you reserve
  some space in memory.

• Based on the data type of a variable, the
  operating system allocates memory and
  decides what can be stored in the reserved
  memory
DATA TYPES
Data Types
• There are two data types available in Java:
      Primitive Data Types
      Reference/Object Data Types

byte:
Byte data type is a 8-bit signed two.s complement integer.
Minimum value is -128 (-2^7)
Maximum value is 127 (inclusive)(2^7 -1)
Default value is 0
Byte data type is used to save space in large arrays, mainly in place
  of integers, since a byte is four times smaller than an int.
Example : byte a = 100 , byte b = -50
short:
Short data type is a 16-bit signed two's
  complement integer.
Minimum value is -32,768 (-2^15)
Maximum value is 32,767(inclusive) (2^15 -1)
Default value is 0.
Example : short s= 10000 , short r = -20000
int:
Int data type is a 32-bit signed two's complement integer.
Minimum value is - 2,147,483,648.(-2^31)
Maximum value is 2,147,483,647(inclusive).(2^31 -1)
Int is generally used as the default data type for integral values
   unless there is a concern about memory.
The default value is 0.
Example : int a = 100000, int b = -200000

long:
Long data type is a 64-bit signed two's complement integer.
Minimum value is -9,223,372,036,854,775,808.(-2^63)
Maximum value is 9,223,372,036,854,775,807 (inclusive). (2^63 -
   1)
This type is used when a wider range than int is needed.
Default value is 0L.
Example : int a = 100000L, int b = -200000L
float:
Float data type is a single-precision 32-bit IEEE 754 floating point.
Float is mainly used to save memory in large arrays of floating point
   numbers.
Default value is 0.0f.
Float data type is never used for precise values such as currency.
Example : float f1 = 234.5f


double:
double data type is a double-precision 64-bit IEEE 754 floating point.
This data type is generally used as the default data type for decimal
  values. generally the default choice.
Double data type should never be used for precise values such as
  currency.
Default value is 0.0d.
Example : double d1 = 123.4
boolean:
boolean data type represents one bit of information.
There are only two possible values : true and false.
This data type is used for simple flags that track
  true/false conditions.
Default value is false.
Example : boolean one = true


char:
char data type is a single 16-bit Unicode character.
Minimum value is 'u0000' (or 0).
Maximum value is 'uffff' (or 65,535 inclusive).
Char data type is used to store any character.
Example . char letterA ='A'
Reference Datatypes
• Reference variables are created using defined
  constructors of the classes. They are used to access
  objects. These variables are declared to be of a specific
  type that cannot be changed. For
  example, Employee, Puppy etc.

• Class objects, and various type of array variables come
  under reference data type.

• Default value of any reference variable is null.

• A reference variable can be used to refer to any object of
  the declared type or any compatible type.

• Example : Animal animal = new Animal("giraffe");
Data Types
DataType   Memory (Bytes)   Range
byte       1                -128 to 127
short      2                -32768 t0 32767
int        4                -2147483648 to 2147483647
long       8                -922337263685477808 to
                            -922337263685477807
float      4                1.4e-045 to 3.4e+038
double     8                4.9e-324 to 1.8e+308
char       2                0 to 65536
boolean    -                True/False
TYPE CONVERSION
   Size Direction of Data Type
      Widening Type Conversion (Casting down)
          Smaller Data Type  Larger Data Type
     Narrowing Type     Conversion (Casting up)
          Larger Data Type  Smaller Data Type


   Conversion done in two ways
     Implicit   type conversion
          Carried out by compiler automatically
     Explicit   type conversion
          Carried out by programmer using casting
Type Conversion

   Widening Type Converstion
     Implicit conversion by compiler automatically


       byte -> short, int, long, float, double
         short -> int, long, float, double
          char -> int, long, float, double
             int -> long, float, double
               long -> float, double
                  float -> double
Type Conversion

   Narrowing Type Conversion
     Programmer    should describe the conversion
      explicitly
                       byte -> char
                   short -> byte, char
                   char -> byte, short
                 int -> byte, short, char
             long -> byte, short, char, int
          float -> byte, short, char, int, long
       double -> byte, short, char, int, long, float
Type Casting

• General form: (targetType) value
  Examples:
   1) integer value will be reduced module bytes
  range:
       int i;
       byte b = (byte) i;
  2) floating-point value will be truncated to
  integer value:
     float f;
     int i = (int) f;
VARIABLES
• type identifier [ = value][, identifier [= value] ...] ;
• Here are several examples of variable declarations of various
   types
 int a, b, c; // declares three ints, a, b, and c.
 int d = 3, e, f = 5; // declares three more ints, initializing
                         // d and f.
 byte z = 22; // initializes z.
double pi = 3.14159; // declares an approximation of pi.
char x = 'x'; // the variable x has the value 'x'.
Types of variables
There are three kinds of variables in Java:
  Local variables
  Instance variables
  Class/static variables

Local variables are declared in methods, constructors, or blocks
Instance variables are declared in a class, but outside a
   method, constructor or any block.
Class variables also known as static variables are declared with
   the static keyword in a class, but outside a
   method, constructor or a block.
Variable Scope
Scope Definition
A scope is defined by a block:

       {
                …
       }

A variable declared inside the scope is not visible outside:

       {
                int   n;
       }
       n = 1;
Example: Variable Scope
class   Scope {
        public static     void main(String      args[]) {
               int x;
               x = 10;
               if (x == 10) {
                       int y = 20;
                       System.out.println("x and y: " + x + “ " + y);

                       x = y * 2;
               }
               System.out.println("x     is   " + x + “y   is”   + y);
        }
}
Variable Lifetime
Variables are created when their scope is entered by control flow and
destroyed when their scope is left:

1) A variable declared in a method will not hold its value between different
    invocations of this method.

2) A variable declared in a block looses its value when the block is left.
3) Initialized in a block, a variable will be re-initialized with every re-entry.

Variables lifetime is confined to its scope!
Example: Variable Lifetime
class   LifeTime   {
        public static    void   main(String     args[])     {
               int x;
               for (x     = 0; x < 3; x++) {
                        int y = -1;
                        System.out.println("y       is:    " + y);
                        y = 100;
                        System.out.println("y       is    now: " + y);
               }
        }
}
OPERATOR TYPES
• Java operators are used to build value expressions.
• Java provides a rich set of operators:
      1) arithmetic      (+,-,*,/,%)
      2) assignment      (+=,-=,*=,/=,%=,=)
      3) relational      (==,!=,<,>,<=,>=)
      4) logical         (&&,||,!)
      5) bitwise         (&,|,~,^,<<,>>,>>)
Bit wise operators
~    ~op             Inverts all bits

&    op1 & op2       Produces 1 bit if both operands are 1

|    op1 |op2        Produces 1 bit if either operand is 1

^    op1 ^ op2       Produces 1 bit if exactly one operand is 1

>>   op1 >> op2      Shifts all bits in op1 right by the value of
                     op2
<<   op1 << op2      Shifts all bits in op1 left by the value of
                     op2
Other Operators
?:           shortcut if-else statement

[]           used to declare arrays, create arrays, access array elements

 .           used to form qualified names

(params)     delimits a comma-separated list of parameters

(type)       casts a value to the specified type

new          creates a new object or a new array

instanceof   determines if its first operand is an instance of the second
Table: Operator Precedence
highest
()        []    .
++        --    ~        !
*         /     %
+         -
>>        >>>   <<
>         >=    <        <=
==        !=
&
^
|
&&
||
?:
=         op=
lowest
Expressions
• An expression is a construct made up of
  variables, operators, and method invocations, which are
  constructed according to the syntax of the language, that
  evaluates to a single value.


• Examples of expressions are in bold below:
  int number = 0;
   anArray[0] = 100;
   System.out.println ("Element 1 at index 0: " + anArray[0]);
   int result = 1 + 2; // result is now 3 if(value1 == value2)
   System.out.println("value1 == value2");
CONTROL STATEMENTS

• Java control statements cause the flow of execution to
  advance and branch based on the changes to the state
  of the program.
• Control statements are divided into three groups:

1) selection statements allow the program to choose
  different parts of the execution based on the outcome
  of an expression
2) iteration statements enable program execution to
  repeat one or more statements
3) jump statements enable your program to execute in a
  non-linear fashion
Selection Statements

• Java selection statements allow to control the flow
  of program’s execution based upon conditions
  known only during run-time.
• Java provides four selection statements:
      1) if
      2) if-else
      3) if-else-if
      4) switch
Iteration Statements


• Java iteration statements enable repeated
  execution of part of a program until a certain
  termination condition becomes true.
• Java provides three iteration statements:
     1) while
     2) do-while
     3) for
     4) for each(JDK1.5 version)
• if-else

Syntax                                   Example


if (<condition-1>) {                      int a = 10;
  // logic for true condition-1 goes here if (a < 10 ) {
} else if (<condition-2>) {                 System.out.println(“Less than 10”);
  // logic for true condition-2 goes here } else if (a > 10) {
} else {                                     System.out.pritln(“Greater than 10”);
  // if no condition is met, control      } else {
comes here                                  System.out.println(“Equal to 10”);
}                                         }

                                         Result: Equal to 10s
•   switch

Syntax               Example

switch (<value>) {   int a = 10;
 case <a>:           switch (a) {
  // stmt-1            case 1:
  break;                System.out.println(“1”);
 case <b>:              break;
  //stmt-2             case 10:
  break;                System.out.println(“10”);
 default:               break;
  //stmt-3             default:
                        System.out.println(“None”);


                     Result: 10
• do-while
    Syntax                    Example
    do {                      int i = 0;
     // stmt-1                do {
    } while (<condition>);    System.out.println(“In do”); i++;
                              } while ( i < 10);

                              Result: Prints “In do” 11 times

• while
    Syntax                   Example

    while (<condition>) {    int i = 0;
              //stmt         while ( i < 10 ) {
    }                          System.out.println(“In while”); i++;
                             }

                             Result: “In while” 10 times
•    for

    Syntax                                  Example


    for ( initialize; condition; expression) for (int i = 0; i < 10; i++)
    {                                        {
      // stmt                                  System.out.println(“In for”);
    }                                        }

                                            Result: Prints “In do” 10 times
Jump Statements

• Java jump statements enable transfer of
  control to other parts of program.
• Java provides three jump statements:
      1) break (3 uses:loop,switch,nested blocks)
      2) continue
      3) return
• In addition, Java supports exception
  handling that can also alter the control flow
  of a program.
TEST




I m not giving the answers for these basic questions,



please try and execute if possible. If you still want the answers


then copy and paste the entire question in google   .
What all gets printed when the following program is compiled and run.
  Select the two correct answers.

  public class test
  {
    public static void main(String args[])
    {
      int i, j=1; i = (j>1)?2:1;
       switch(i)
        {
           case 0: System.out.println(0); break;
           case 1: System.out.println(1);
           case 2: System.out.println(2); break;
           case 3: System.out.println(3); break;
         }
    }
}
 a) 0
 b) 1
 c) 2
 d) 3
Which declaration of the main method below
  would allow a class to be started as a
  standalone program. Select the one correct
  answer.


a) public static void main(String args[])
b) public static void MAIN(String args[])
c) public static void main(String args)
d) public static void main(char args[])
e) static public void main(String args[])
f) public static int main(char args[])
Which of the following will compile without error

1) import java.awt.*;
   package Mypackage;
   class Myclass {}

2) package MyPackage;
   import java.awt.*;
   class MyClass{}

3) /*This is a comment */
  package MyPackage;
  import java.awt.*;
  class MyClass{}
What’s the difference between
constructors and normal methods?



Constructors must have the same name
as the class and can not return a value.
They are only called once
while regular methods could be called many
times and it can return a value or can be
void.
• Give a simplest way to find out the time a
  method takes for execution without
  using any profiling tool?

 long start = System.currentTimeMillis ();
 method ();
 long end = System.currentTimeMillis ();

 System.out.println (“Time taken for execution is ” + (end –
 start));
public class test
 {
   public static void main(String args[])
    {
      String s1 = "abc";
      String s2 = "abc";
          if(s1 == s2)
             System.out.println(1);
         else
             System.out.println(2);
           if(s1.equals(s2))
               System.out.println(3);
             else
               System.out.println(4);
}
}
a)1
b)2
c)3
d)4
• Which of the following are legal array
  declarations. Select the three correct
  answers.



a) int i[5][];
b) int i[][];
c) int []i[];
d) int i[5][5];
e) int[][] a;
What is the range of values that can be
  specified for an int. Select the one correct
  answer. The range of values is compiler
  dependent.

a) -231 to 231 - 1
b) -231-1 to 231
c) -215 to 215 - 1
d) -215-1 to 215
What would be the results of compiling and running the following
  class. Select the one correct answer.

  class test
     {
       public static void main()
        {
           System.out.println("test");
         }
     }

a)The program does not compile as there is no main method
   defined.
b)The program compiles and runs generating an output of "test"
c)The program compiles and runs but does not generate any
   output.
d)The program compiles but does not run.
What gets printed when the following program is compiled and
  run. Select the one correct answer.

class test {
   public static void main(String args[]) {
        int i,j,k,l=0;
        k = l++;
        j = ++k;
        i = j++;
        System.out.println(i);
   }
}

    a) 0
    b) 1
    c) 2
    d) 3
• Which operator is used to perform bitwise
  inversion in Java. Select the one correct
  answer.

  a) ~
  b) !
  c) &
  d)|
  e) ^
What gets printed when the following program is compiled and run. Select the one
  correct answer.


public class test {
   public static void main(String args[]) {
          byte x = 3;
          x = (byte)~x;
          System.out.println(x);
   }
}


    a) 3
    b) 0
    c) 1
    d) 11
    e) 252
    f) 214
    g) 124
    h) -4
What gets displayed on the screen when the following program is compiled and
  run. Select the one correct answer.

public class test {
   public static void main(String args[]) {
          int x,y;
          x = 3 & 5;
          y = 3 | 5;
          System.out.println(x + " " + y);
   }
}

    a) 7 1
    b) 3 7
    c) 1 7
    d) 3 1
    e) 1 3
    f) 7 3
    g) 7 5
What all gets printed when the following program is compiled
  and run. Select the one correct answer.

public class test {
    public static void main(String args[])
   {
      int i=0, j=2;
     do {
           i=++i;
            j--;
          }
       while(j>0);
System.out.println(i);
}
}
a)   0
b)   1
c)   2
d)    The program does not compile because of statement "i=++i;"
What gets displayed on the screen when the following program is
  compiled and run. Select the one correct answer.

public class test {
  public static void main(String args[]) {
         int x, y;

           x = 5 >> 2;
           y = x >>> 2;
           System.out.println(y);
    }
}

        a) 5
        b) 2
        c) 80
        d) 0
        e) 64
Thank You

Más contenido relacionado

La actualidad más candente

La actualidad más candente (20)

Introduction to java and oop
Introduction to java and oopIntroduction to java and oop
Introduction to java and oop
 
Unit 2
Unit 2Unit 2
Unit 2
 
Intro to Object Oriented Programming with Java
Intro to Object Oriented Programming with Java Intro to Object Oriented Programming with Java
Intro to Object Oriented Programming with Java
 
OOPs in Java
OOPs in JavaOOPs in Java
OOPs in Java
 
Core java lessons
Core java lessonsCore java lessons
Core java lessons
 
Java Object Oriented Programming
Java Object Oriented Programming Java Object Oriented Programming
Java Object Oriented Programming
 
Comp102 lec 3
Comp102   lec 3Comp102   lec 3
Comp102 lec 3
 
Object oriented concepts with java
Object oriented concepts with javaObject oriented concepts with java
Object oriented concepts with java
 
Basic concepts of object oriented programming
Basic concepts of object oriented programmingBasic concepts of object oriented programming
Basic concepts of object oriented programming
 
Presentation on java
Presentation  on  javaPresentation  on  java
Presentation on java
 
Oops concepts || Object Oriented Programming Concepts in Java
Oops concepts || Object Oriented Programming Concepts in JavaOops concepts || Object Oriented Programming Concepts in Java
Oops concepts || Object Oriented Programming Concepts in Java
 
Core Java
Core JavaCore Java
Core Java
 
Review Session and Attending Java Interviews
Review Session and Attending Java Interviews Review Session and Attending Java Interviews
Review Session and Attending Java Interviews
 
JAVA PROGRAMMING- Exception handling - Multithreading
JAVA PROGRAMMING- Exception handling - MultithreadingJAVA PROGRAMMING- Exception handling - Multithreading
JAVA PROGRAMMING- Exception handling - Multithreading
 
JAVA PROGRAMMING – Packages - Stream based I/O
JAVA PROGRAMMING – Packages - Stream based I/O JAVA PROGRAMMING – Packages - Stream based I/O
JAVA PROGRAMMING – Packages - Stream based I/O
 
Java object oriented programming concepts - Brainsmartlabs
Java object oriented programming concepts - BrainsmartlabsJava object oriented programming concepts - Brainsmartlabs
Java object oriented programming concepts - Brainsmartlabs
 
Oops ppt
Oops pptOops ppt
Oops ppt
 
Mcs 024 assignment solution (2020-21)
Mcs 024 assignment solution (2020-21)Mcs 024 assignment solution (2020-21)
Mcs 024 assignment solution (2020-21)
 
OOP Introduction with java programming language
OOP Introduction with java programming languageOOP Introduction with java programming language
OOP Introduction with java programming language
 
Introduction to oop using java
Introduction  to oop using java Introduction  to oop using java
Introduction to oop using java
 

Destacado

Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVA
Abhilash Nair
 
Marketingplan LR
Marketingplan LRMarketingplan LR
Marketingplan LR
t575ae
 

Destacado (20)

Exception handling
Exception handlingException handling
Exception handling
 
String handling session 5
String handling session 5String handling session 5
String handling session 5
 
Java interfaces
Java interfacesJava interfaces
Java interfaces
 
Java packages
Java packagesJava packages
Java packages
 
Class object method constructors in java
Class object method constructors in javaClass object method constructors in java
Class object method constructors in java
 
Ppt on java basics1
Ppt on java basics1Ppt on java basics1
Ppt on java basics1
 
ANDROID FDP PPT
ANDROID FDP PPTANDROID FDP PPT
ANDROID FDP PPT
 
Java ppt Gandhi Ravi (gandhiri@gmail.com)
Java ppt  Gandhi Ravi  (gandhiri@gmail.com)Java ppt  Gandhi Ravi  (gandhiri@gmail.com)
Java ppt Gandhi Ravi (gandhiri@gmail.com)
 
Introduction to class in java
Introduction to class in javaIntroduction to class in java
Introduction to class in java
 
Oop java
Oop javaOop java
Oop java
 
Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVA
 
Java Basics for selenium
Java Basics for seleniumJava Basics for selenium
Java Basics for selenium
 
Method overloading and constructor overloading in java
Method overloading and constructor overloading in javaMethod overloading and constructor overloading in java
Method overloading and constructor overloading in java
 
Constructor in java
Constructor in javaConstructor in java
Constructor in java
 
Constructor ppt
Constructor pptConstructor ppt
Constructor ppt
 
Test
TestTest
Test
 
京田辺市関西観光拠点化計画
京田辺市関西観光拠点化計画京田辺市関西観光拠点化計画
京田辺市関西観光拠点化計画
 
Mobile Your Data | AdvantageNFP | CHASE 2011 Seminar
Mobile Your Data | AdvantageNFP | CHASE 2011 Seminar Mobile Your Data | AdvantageNFP | CHASE 2011 Seminar
Mobile Your Data | AdvantageNFP | CHASE 2011 Seminar
 
Marketingplan LR
Marketingplan LRMarketingplan LR
Marketingplan LR
 
MY NAME IS DUBIAN MARIN - UNAD
MY NAME IS DUBIAN MARIN - UNADMY NAME IS DUBIAN MARIN - UNAD
MY NAME IS DUBIAN MARIN - UNAD
 

Similar a java Basic Programming Needs

C language presentation
C language presentationC language presentation
C language presentation
bainspreet
 
Java fundamentals
Java fundamentalsJava fundamentals
Java fundamentals
HCMUTE
 

Similar a java Basic Programming Needs (20)

Cpprm
CpprmCpprm
Cpprm
 
Identifiers, keywords and types
Identifiers, keywords and typesIdentifiers, keywords and types
Identifiers, keywords and types
 
Java - Basic Datatypes.pptx
Java - Basic Datatypes.pptxJava - Basic Datatypes.pptx
Java - Basic Datatypes.pptx
 
Data types
Data typesData types
Data types
 
Chapter 2.datatypes and operators
Chapter 2.datatypes and operatorsChapter 2.datatypes and operators
Chapter 2.datatypes and operators
 
java tutorial 2
 java tutorial 2 java tutorial 2
java tutorial 2
 
Lecture - 3 Variables-data type_operators_oops concept
Lecture - 3 Variables-data type_operators_oops conceptLecture - 3 Variables-data type_operators_oops concept
Lecture - 3 Variables-data type_operators_oops concept
 
C language presentation
C language presentationC language presentation
C language presentation
 
03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...
 
Java fundamentals
Java fundamentalsJava fundamentals
Java fundamentals
 
Java Datatypes
Java DatatypesJava Datatypes
Java Datatypes
 
Data Handling
Data HandlingData Handling
Data Handling
 
02 functions, variables, basic input and output of c++
02   functions, variables, basic input and output of c++02   functions, variables, basic input and output of c++
02 functions, variables, basic input and output of c++
 
Unit 2-data types,Variables,Operators,Conitionals,loops and arrays
Unit 2-data types,Variables,Operators,Conitionals,loops and arraysUnit 2-data types,Variables,Operators,Conitionals,loops and arrays
Unit 2-data types,Variables,Operators,Conitionals,loops and arrays
 
primitive data types
 primitive data types primitive data types
primitive data types
 
Python basics
Python basicsPython basics
Python basics
 
Data types and Operators
Data types and OperatorsData types and Operators
Data types and Operators
 
Introduction to c
Introduction to cIntroduction to c
Introduction to c
 
OOP-java-variables.pptx
OOP-java-variables.pptxOOP-java-variables.pptx
OOP-java-variables.pptx
 
Pj01 3-java-variable and data types
Pj01 3-java-variable and data typesPj01 3-java-variable and data types
Pj01 3-java-variable and data types
 

Último

1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
QucHHunhnh
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please Practise
AnaAcapella
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
negromaestrong
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
ciinovamais
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
ZurliaSoop
 

Último (20)

Spatium Project Simulation student brief
Spatium Project Simulation student briefSpatium Project Simulation student brief
Spatium Project Simulation student brief
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please Practise
 
Magic bus Group work1and 2 (Team 3).pptx
Magic bus Group work1and 2 (Team 3).pptxMagic bus Group work1and 2 (Team 3).pptx
Magic bus Group work1and 2 (Team 3).pptx
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701
 
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxSKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
 
Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
 
Dyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptxDyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptx
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docx
 

java Basic Programming Needs

  • 2. Contents… Data Types Type Conversion and Casting Variables Scope and lifetime of variables Operators Expressions Control Statements
  • 3. DATA TYPES • Variables are nothing but reserved memory locations to store values. This means that when you create a variable you reserve some space in memory. • Based on the data type of a variable, the operating system allocates memory and decides what can be stored in the reserved memory
  • 5. Data Types • There are two data types available in Java: Primitive Data Types Reference/Object Data Types byte: Byte data type is a 8-bit signed two.s complement integer. Minimum value is -128 (-2^7) Maximum value is 127 (inclusive)(2^7 -1) Default value is 0 Byte data type is used to save space in large arrays, mainly in place of integers, since a byte is four times smaller than an int. Example : byte a = 100 , byte b = -50
  • 6. short: Short data type is a 16-bit signed two's complement integer. Minimum value is -32,768 (-2^15) Maximum value is 32,767(inclusive) (2^15 -1) Default value is 0. Example : short s= 10000 , short r = -20000
  • 7. int: Int data type is a 32-bit signed two's complement integer. Minimum value is - 2,147,483,648.(-2^31) Maximum value is 2,147,483,647(inclusive).(2^31 -1) Int is generally used as the default data type for integral values unless there is a concern about memory. The default value is 0. Example : int a = 100000, int b = -200000 long: Long data type is a 64-bit signed two's complement integer. Minimum value is -9,223,372,036,854,775,808.(-2^63) Maximum value is 9,223,372,036,854,775,807 (inclusive). (2^63 - 1) This type is used when a wider range than int is needed. Default value is 0L. Example : int a = 100000L, int b = -200000L
  • 8. float: Float data type is a single-precision 32-bit IEEE 754 floating point. Float is mainly used to save memory in large arrays of floating point numbers. Default value is 0.0f. Float data type is never used for precise values such as currency. Example : float f1 = 234.5f double: double data type is a double-precision 64-bit IEEE 754 floating point. This data type is generally used as the default data type for decimal values. generally the default choice. Double data type should never be used for precise values such as currency. Default value is 0.0d. Example : double d1 = 123.4
  • 9. boolean: boolean data type represents one bit of information. There are only two possible values : true and false. This data type is used for simple flags that track true/false conditions. Default value is false. Example : boolean one = true char: char data type is a single 16-bit Unicode character. Minimum value is 'u0000' (or 0). Maximum value is 'uffff' (or 65,535 inclusive). Char data type is used to store any character. Example . char letterA ='A'
  • 10. Reference Datatypes • Reference variables are created using defined constructors of the classes. They are used to access objects. These variables are declared to be of a specific type that cannot be changed. For example, Employee, Puppy etc. • Class objects, and various type of array variables come under reference data type. • Default value of any reference variable is null. • A reference variable can be used to refer to any object of the declared type or any compatible type. • Example : Animal animal = new Animal("giraffe");
  • 11. Data Types DataType Memory (Bytes) Range byte 1 -128 to 127 short 2 -32768 t0 32767 int 4 -2147483648 to 2147483647 long 8 -922337263685477808 to -922337263685477807 float 4 1.4e-045 to 3.4e+038 double 8 4.9e-324 to 1.8e+308 char 2 0 to 65536 boolean - True/False
  • 12. TYPE CONVERSION  Size Direction of Data Type  Widening Type Conversion (Casting down)  Smaller Data Type  Larger Data Type  Narrowing Type Conversion (Casting up)  Larger Data Type  Smaller Data Type  Conversion done in two ways  Implicit type conversion  Carried out by compiler automatically  Explicit type conversion  Carried out by programmer using casting
  • 13. Type Conversion  Widening Type Converstion  Implicit conversion by compiler automatically byte -> short, int, long, float, double short -> int, long, float, double char -> int, long, float, double int -> long, float, double long -> float, double float -> double
  • 14. Type Conversion  Narrowing Type Conversion  Programmer should describe the conversion explicitly byte -> char short -> byte, char char -> byte, short int -> byte, short, char long -> byte, short, char, int float -> byte, short, char, int, long double -> byte, short, char, int, long, float
  • 15. Type Casting • General form: (targetType) value Examples: 1) integer value will be reduced module bytes range: int i; byte b = (byte) i; 2) floating-point value will be truncated to integer value: float f; int i = (int) f;
  • 16. VARIABLES • type identifier [ = value][, identifier [= value] ...] ; • Here are several examples of variable declarations of various types int a, b, c; // declares three ints, a, b, and c. int d = 3, e, f = 5; // declares three more ints, initializing // d and f. byte z = 22; // initializes z. double pi = 3.14159; // declares an approximation of pi. char x = 'x'; // the variable x has the value 'x'.
  • 17. Types of variables There are three kinds of variables in Java: Local variables Instance variables Class/static variables Local variables are declared in methods, constructors, or blocks Instance variables are declared in a class, but outside a method, constructor or any block. Class variables also known as static variables are declared with the static keyword in a class, but outside a method, constructor or a block.
  • 19. Scope Definition A scope is defined by a block: { … } A variable declared inside the scope is not visible outside: { int n; } n = 1;
  • 20. Example: Variable Scope class Scope { public static void main(String args[]) { int x; x = 10; if (x == 10) { int y = 20; System.out.println("x and y: " + x + “ " + y); x = y * 2; } System.out.println("x is " + x + “y is” + y); } }
  • 21. Variable Lifetime Variables are created when their scope is entered by control flow and destroyed when their scope is left: 1) A variable declared in a method will not hold its value between different invocations of this method. 2) A variable declared in a block looses its value when the block is left. 3) Initialized in a block, a variable will be re-initialized with every re-entry. Variables lifetime is confined to its scope!
  • 22. Example: Variable Lifetime class LifeTime { public static void main(String args[]) { int x; for (x = 0; x < 3; x++) { int y = -1; System.out.println("y is: " + y); y = 100; System.out.println("y is now: " + y); } } }
  • 23. OPERATOR TYPES • Java operators are used to build value expressions. • Java provides a rich set of operators: 1) arithmetic (+,-,*,/,%) 2) assignment (+=,-=,*=,/=,%=,=) 3) relational (==,!=,<,>,<=,>=) 4) logical (&&,||,!) 5) bitwise (&,|,~,^,<<,>>,>>)
  • 24. Bit wise operators ~ ~op Inverts all bits & op1 & op2 Produces 1 bit if both operands are 1 | op1 |op2 Produces 1 bit if either operand is 1 ^ op1 ^ op2 Produces 1 bit if exactly one operand is 1 >> op1 >> op2 Shifts all bits in op1 right by the value of op2 << op1 << op2 Shifts all bits in op1 left by the value of op2
  • 25. Other Operators ?: shortcut if-else statement [] used to declare arrays, create arrays, access array elements . used to form qualified names (params) delimits a comma-separated list of parameters (type) casts a value to the specified type new creates a new object or a new array instanceof determines if its first operand is an instance of the second
  • 26. Table: Operator Precedence highest () [] . ++ -- ~ ! * / % + - >> >>> << > >= < <= == != & ^ | && || ?: = op= lowest
  • 27. Expressions • An expression is a construct made up of variables, operators, and method invocations, which are constructed according to the syntax of the language, that evaluates to a single value. • Examples of expressions are in bold below: int number = 0; anArray[0] = 100; System.out.println ("Element 1 at index 0: " + anArray[0]); int result = 1 + 2; // result is now 3 if(value1 == value2) System.out.println("value1 == value2");
  • 28. CONTROL STATEMENTS • Java control statements cause the flow of execution to advance and branch based on the changes to the state of the program. • Control statements are divided into three groups: 1) selection statements allow the program to choose different parts of the execution based on the outcome of an expression 2) iteration statements enable program execution to repeat one or more statements 3) jump statements enable your program to execute in a non-linear fashion
  • 29. Selection Statements • Java selection statements allow to control the flow of program’s execution based upon conditions known only during run-time. • Java provides four selection statements: 1) if 2) if-else 3) if-else-if 4) switch
  • 30. Iteration Statements • Java iteration statements enable repeated execution of part of a program until a certain termination condition becomes true. • Java provides three iteration statements: 1) while 2) do-while 3) for 4) for each(JDK1.5 version)
  • 31. • if-else Syntax Example if (<condition-1>) { int a = 10; // logic for true condition-1 goes here if (a < 10 ) { } else if (<condition-2>) { System.out.println(“Less than 10”); // logic for true condition-2 goes here } else if (a > 10) { } else { System.out.pritln(“Greater than 10”); // if no condition is met, control } else { comes here System.out.println(“Equal to 10”); } } Result: Equal to 10s
  • 32. switch Syntax Example switch (<value>) { int a = 10; case <a>: switch (a) { // stmt-1 case 1: break; System.out.println(“1”); case <b>: break; //stmt-2 case 10: break; System.out.println(“10”); default: break; //stmt-3 default: System.out.println(“None”); Result: 10
  • 33. • do-while Syntax Example do { int i = 0; // stmt-1 do { } while (<condition>); System.out.println(“In do”); i++; } while ( i < 10); Result: Prints “In do” 11 times • while Syntax Example while (<condition>) { int i = 0; //stmt while ( i < 10 ) { } System.out.println(“In while”); i++; } Result: “In while” 10 times
  • 34. for Syntax Example for ( initialize; condition; expression) for (int i = 0; i < 10; i++) { { // stmt System.out.println(“In for”); } } Result: Prints “In do” 10 times
  • 35. Jump Statements • Java jump statements enable transfer of control to other parts of program. • Java provides three jump statements: 1) break (3 uses:loop,switch,nested blocks) 2) continue 3) return • In addition, Java supports exception handling that can also alter the control flow of a program.
  • 36. TEST I m not giving the answers for these basic questions, please try and execute if possible. If you still want the answers then copy and paste the entire question in google .
  • 37. What all gets printed when the following program is compiled and run. Select the two correct answers. public class test { public static void main(String args[]) { int i, j=1; i = (j>1)?2:1; switch(i) { case 0: System.out.println(0); break; case 1: System.out.println(1); case 2: System.out.println(2); break; case 3: System.out.println(3); break; } } } a) 0 b) 1 c) 2 d) 3
  • 38. Which declaration of the main method below would allow a class to be started as a standalone program. Select the one correct answer. a) public static void main(String args[]) b) public static void MAIN(String args[]) c) public static void main(String args) d) public static void main(char args[]) e) static public void main(String args[]) f) public static int main(char args[])
  • 39. Which of the following will compile without error 1) import java.awt.*; package Mypackage; class Myclass {} 2) package MyPackage; import java.awt.*; class MyClass{} 3) /*This is a comment */ package MyPackage; import java.awt.*; class MyClass{}
  • 40. What’s the difference between constructors and normal methods? Constructors must have the same name as the class and can not return a value. They are only called once while regular methods could be called many times and it can return a value or can be void.
  • 41. • Give a simplest way to find out the time a method takes for execution without using any profiling tool? long start = System.currentTimeMillis (); method (); long end = System.currentTimeMillis (); System.out.println (“Time taken for execution is ” + (end – start));
  • 42. public class test { public static void main(String args[]) { String s1 = "abc"; String s2 = "abc"; if(s1 == s2) System.out.println(1); else System.out.println(2); if(s1.equals(s2)) System.out.println(3); else System.out.println(4); } } a)1 b)2 c)3 d)4
  • 43. • Which of the following are legal array declarations. Select the three correct answers. a) int i[5][]; b) int i[][]; c) int []i[]; d) int i[5][5]; e) int[][] a;
  • 44. What is the range of values that can be specified for an int. Select the one correct answer. The range of values is compiler dependent. a) -231 to 231 - 1 b) -231-1 to 231 c) -215 to 215 - 1 d) -215-1 to 215
  • 45. What would be the results of compiling and running the following class. Select the one correct answer. class test { public static void main() { System.out.println("test"); } } a)The program does not compile as there is no main method defined. b)The program compiles and runs generating an output of "test" c)The program compiles and runs but does not generate any output. d)The program compiles but does not run.
  • 46. What gets printed when the following program is compiled and run. Select the one correct answer. class test { public static void main(String args[]) { int i,j,k,l=0; k = l++; j = ++k; i = j++; System.out.println(i); } } a) 0 b) 1 c) 2 d) 3
  • 47. • Which operator is used to perform bitwise inversion in Java. Select the one correct answer. a) ~ b) ! c) & d)| e) ^
  • 48. What gets printed when the following program is compiled and run. Select the one correct answer. public class test { public static void main(String args[]) { byte x = 3; x = (byte)~x; System.out.println(x); } } a) 3 b) 0 c) 1 d) 11 e) 252 f) 214 g) 124 h) -4
  • 49. What gets displayed on the screen when the following program is compiled and run. Select the one correct answer. public class test { public static void main(String args[]) { int x,y; x = 3 & 5; y = 3 | 5; System.out.println(x + " " + y); } } a) 7 1 b) 3 7 c) 1 7 d) 3 1 e) 1 3 f) 7 3 g) 7 5
  • 50. What all gets printed when the following program is compiled and run. Select the one correct answer. public class test { public static void main(String args[]) { int i=0, j=2; do { i=++i; j--; } while(j>0); System.out.println(i); } } a) 0 b) 1 c) 2 d) The program does not compile because of statement "i=++i;"
  • 51. What gets displayed on the screen when the following program is compiled and run. Select the one correct answer. public class test { public static void main(String args[]) { int x, y; x = 5 >> 2; y = x >>> 2; System.out.println(y); } } a) 5 b) 2 c) 80 d) 0 e) 64