SlideShare a Scribd company logo
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

More Related Content

What's hot (20)

PDF
Introduction to java and oop
baabtra.com - No. 1 supplier of quality freshers
 
PDF
Unit 2
Amar Jukuntla
 
PPSX
Intro to Object Oriented Programming with Java
Hitesh-Java
 
PPTX
OOPs in Java
Ranjith Sekar
 
PPSX
Core java lessons
vivek shah
 
PPSX
Java Object Oriented Programming
University of Potsdam
 
PPT
Comp102 lec 3
Fraz Bakhsh
 
PPTX
Object oriented concepts with java
ishmecse13
 
PPT
Basic concepts of object oriented programming
Sachin Sharma
 
PPT
Presentation on java
shashi shekhar
 
PDF
Oops concepts || Object Oriented Programming Concepts in Java
Madishetty Prathibha
 
PDF
Core Java
Prakash Dimmita
 
PPSX
Review Session and Attending Java Interviews
Hitesh-Java
 
PDF
JAVA PROGRAMMING- Exception handling - Multithreading
Jyothishmathi Institute of Technology and Science Karimnagar
 
PDF
JAVA PROGRAMMING – Packages - Stream based I/O
Jyothishmathi Institute of Technology and Science Karimnagar
 
PPTX
Java object oriented programming concepts - Brainsmartlabs
brainsmartlabsedu
 
PPT
Oops ppt
abhayjuneja
 
DOCX
Mcs 024 assignment solution (2020-21)
smumbahelp
 
PPTX
OOP Introduction with java programming language
Md.Al-imran Roton
 
PPTX
Introduction to oop using java
omeed
 
Intro to Object Oriented Programming with Java
Hitesh-Java
 
OOPs in Java
Ranjith Sekar
 
Core java lessons
vivek shah
 
Java Object Oriented Programming
University of Potsdam
 
Comp102 lec 3
Fraz Bakhsh
 
Object oriented concepts with java
ishmecse13
 
Basic concepts of object oriented programming
Sachin Sharma
 
Presentation on java
shashi shekhar
 
Oops concepts || Object Oriented Programming Concepts in Java
Madishetty Prathibha
 
Core Java
Prakash Dimmita
 
Review Session and Attending Java Interviews
Hitesh-Java
 
JAVA PROGRAMMING- Exception handling - Multithreading
Jyothishmathi Institute of Technology and Science Karimnagar
 
JAVA PROGRAMMING – Packages - Stream based I/O
Jyothishmathi Institute of Technology and Science Karimnagar
 
Java object oriented programming concepts - Brainsmartlabs
brainsmartlabsedu
 
Oops ppt
abhayjuneja
 
Mcs 024 assignment solution (2020-21)
smumbahelp
 
OOP Introduction with java programming language
Md.Al-imran Roton
 
Introduction to oop using java
omeed
 

Viewers also liked (20)

PPT
Exception handling
Raja Sekhar
 
PPT
String handling session 5
Raja Sekhar
 
PPT
Java interfaces
Raja Sekhar
 
PPT
Java packages
Raja Sekhar
 
PPTX
Class object method constructors in java
Raja Sekhar
 
PPTX
Ppt on java basics1
Mavoori Soshmitha
 
PPT
ANDROID FDP PPT
skumartarget
 
PDF
Java ppt Gandhi Ravi ([email protected])
Gandhi Ravi
 
PPS
Introduction to class in java
kamal kotecha
 
PPT
Oop java
Minal Maniar
 
PPTX
Classes, objects in JAVA
Abhilash Nair
 
PPT
Java Basics for selenium
apoorvams
 
PPTX
Method overloading and constructor overloading in java
baabtra.com - No. 1 supplier of quality freshers
 
PPTX
Constructor in java
Hitesh Kumar
 
PPTX
Constructor ppt
Vinod Kumar
 
PPT
Test
hophuong0208
 
PPT
京田辺市関西観光拠点化計画
Fumihiro Koide
 
PPTX
Mobile Your Data | AdvantageNFP | CHASE 2011 Seminar
Redbourn Business Systems
 
PDF
Marketingplan LR
t575ae
 
PPTX
MY NAME IS DUBIAN MARIN - UNAD
Dubian Marin Rodriguez
 
Exception handling
Raja Sekhar
 
String handling session 5
Raja Sekhar
 
Java interfaces
Raja Sekhar
 
Java packages
Raja Sekhar
 
Class object method constructors in java
Raja Sekhar
 
Ppt on java basics1
Mavoori Soshmitha
 
ANDROID FDP PPT
skumartarget
 
Java ppt Gandhi Ravi ([email protected])
Gandhi Ravi
 
Introduction to class in java
kamal kotecha
 
Oop java
Minal Maniar
 
Classes, objects in JAVA
Abhilash Nair
 
Java Basics for selenium
apoorvams
 
Method overloading and constructor overloading in java
baabtra.com - No. 1 supplier of quality freshers
 
Constructor in java
Hitesh Kumar
 
Constructor ppt
Vinod Kumar
 
京田辺市関西観光拠点化計画
Fumihiro Koide
 
Mobile Your Data | AdvantageNFP | CHASE 2011 Seminar
Redbourn Business Systems
 
Marketingplan LR
t575ae
 
MY NAME IS DUBIAN MARIN - UNAD
Dubian Marin Rodriguez
 
Ad

Similar to java Basic Programming Needs (20)

PPTX
Java fundamentals
HCMUTE
 
PPTX
Data types in java.pptx power point of java
rabiyanaseer1
 
PPTX
Java Datatypes
Mayank Aggarwal
 
PPTX
Android webinar class_java_review
Edureka!
 
PPTX
Introduction to Java Basics Programming-II.pptx
SANDHYAP32
 
PPTX
Chapter i(introduction to java)
Chhom Karath
 
PPTX
OOP - Lecture04 - Variables, DataTypes and TypeConversion.pptx
AhmedMehmood35
 
PPT
Md03 - part3
Rakesh Madugula
 
PPTX
Unit-1 Data Types and Operators.pptx to computers
csangani1
 
PPTX
Learning core java
Abhay Bharti
 
PPTX
L2 datatypes and variables
teach4uin
 
PPT
demo1 java of demo 1 java with demo 1 java.ppt
FerdieBalang
 
PPTX
Identifiers, keywords and types
Daman Toor
 
PDF
Sdtl manual
qaz8989
 
PPTX
Java chapter 2
Abdii Rashid
 
PDF
Shiksharth com java_topics
Rajesh Verma
 
PPT
2.DATA TYPES_MB_2022.ppt .
happycocoman
 
PPTX
03 and 04 .Operators, Expressions, working with the console and conditional s...
Intro C# Book
 
PPT
java tutorial 2
Tushar Desarda
 
Java fundamentals
HCMUTE
 
Data types in java.pptx power point of java
rabiyanaseer1
 
Java Datatypes
Mayank Aggarwal
 
Android webinar class_java_review
Edureka!
 
Introduction to Java Basics Programming-II.pptx
SANDHYAP32
 
Chapter i(introduction to java)
Chhom Karath
 
OOP - Lecture04 - Variables, DataTypes and TypeConversion.pptx
AhmedMehmood35
 
Md03 - part3
Rakesh Madugula
 
Unit-1 Data Types and Operators.pptx to computers
csangani1
 
Learning core java
Abhay Bharti
 
L2 datatypes and variables
teach4uin
 
demo1 java of demo 1 java with demo 1 java.ppt
FerdieBalang
 
Identifiers, keywords and types
Daman Toor
 
Sdtl manual
qaz8989
 
Java chapter 2
Abdii Rashid
 
Shiksharth com java_topics
Rajesh Verma
 
2.DATA TYPES_MB_2022.ppt .
happycocoman
 
03 and 04 .Operators, Expressions, working with the console and conditional s...
Intro C# Book
 
java tutorial 2
Tushar Desarda
 
Ad

Recently uploaded (20)

PDF
The History of Phone Numbers in Stoke Newington by Billy Thomas
History of Stoke Newington
 
PPTX
Identifying elements in the story. Arrange the events in the story
geraldineamahido2
 
PDF
ARAL-Orientation_Morning-Session_Day-11.pdf
JoelVilloso1
 
PPTX
How to Create Odoo JS Dialog_Popup in Odoo 18
Celine George
 
PPTX
care of patient with elimination needs.pptx
Rekhanjali Gupta
 
PPT
Talk on Critical Theory, Part One, Philosophy of Social Sciences
Soraj Hongladarom
 
PPTX
QUARTER 1 WEEK 2 PLOT, POV AND CONFLICTS
KynaParas
 
PPTX
Unit 2 COMMERCIAL BANKING, Corporate banking.pptx
AnubalaSuresh1
 
PDF
0725.WHITEPAPER-UNIQUEWAYSOFPROTOTYPINGANDUXNOW.pdf
Thomas GIRARD, MA, CDP
 
PPTX
Universal immunization Programme (UIP).pptx
Vishal Chanalia
 
PPTX
A PPT on Alfred Lord Tennyson's Ulysses.
Beena E S
 
PPTX
CATEGORIES OF NURSING PERSONNEL: HOSPITAL & COLLEGE
PRADEEP ABOTHU
 
PDF
The Different Types of Non-Experimental Research
Thelma Villaflores
 
PPTX
Cultivation practice of Litchi in Nepal.pptx
UmeshTimilsina1
 
PDF
Stokey: A Jewish Village by Rachel Kolsky
History of Stoke Newington
 
PDF
Chapter-V-DED-Entrepreneurship: Institutions Facilitating Entrepreneurship
Dayanand Huded
 
PPTX
MENINGITIS: NURSING MANAGEMENT, BACTERIAL MENINGITIS, VIRAL MENINGITIS.pptx
PRADEEP ABOTHU
 
PPTX
ASRB NET 2023 PREVIOUS YEAR QUESTION PAPER GENETICS AND PLANT BREEDING BY SAT...
Krashi Coaching
 
PPTX
How to Create a PDF Report in Odoo 18 - Odoo Slides
Celine George
 
PDF
Exploring the Different Types of Experimental Research
Thelma Villaflores
 
The History of Phone Numbers in Stoke Newington by Billy Thomas
History of Stoke Newington
 
Identifying elements in the story. Arrange the events in the story
geraldineamahido2
 
ARAL-Orientation_Morning-Session_Day-11.pdf
JoelVilloso1
 
How to Create Odoo JS Dialog_Popup in Odoo 18
Celine George
 
care of patient with elimination needs.pptx
Rekhanjali Gupta
 
Talk on Critical Theory, Part One, Philosophy of Social Sciences
Soraj Hongladarom
 
QUARTER 1 WEEK 2 PLOT, POV AND CONFLICTS
KynaParas
 
Unit 2 COMMERCIAL BANKING, Corporate banking.pptx
AnubalaSuresh1
 
0725.WHITEPAPER-UNIQUEWAYSOFPROTOTYPINGANDUXNOW.pdf
Thomas GIRARD, MA, CDP
 
Universal immunization Programme (UIP).pptx
Vishal Chanalia
 
A PPT on Alfred Lord Tennyson's Ulysses.
Beena E S
 
CATEGORIES OF NURSING PERSONNEL: HOSPITAL & COLLEGE
PRADEEP ABOTHU
 
The Different Types of Non-Experimental Research
Thelma Villaflores
 
Cultivation practice of Litchi in Nepal.pptx
UmeshTimilsina1
 
Stokey: A Jewish Village by Rachel Kolsky
History of Stoke Newington
 
Chapter-V-DED-Entrepreneurship: Institutions Facilitating Entrepreneurship
Dayanand Huded
 
MENINGITIS: NURSING MANAGEMENT, BACTERIAL MENINGITIS, VIRAL MENINGITIS.pptx
PRADEEP ABOTHU
 
ASRB NET 2023 PREVIOUS YEAR QUESTION PAPER GENETICS AND PLANT BREEDING BY SAT...
Krashi Coaching
 
How to Create a PDF Report in Odoo 18 - Odoo Slides
Celine George
 
Exploring the Different Types of Experimental Research
Thelma Villaflores
 

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