Java Basics

First program in java

/* This is a simple Java program.
  Call this file "Example.java".
*/
class Example {
// Your program begins with a call to main().
      public static void main(String args[]) {
      System.out.println("This is a simple Java program.");
}//End of main

}//End of class


Compiling java program


C:\>javac Example.java


Run java program

c:/java Example


Datatypes: 
                     byte, short, int, long, char, float, double


Scope and Lifetime of Variables

int x=10;
      if(x==10)
              int y = 20;
           
              System.out.println("x and y: " + x + " " + y);  // x and y both known here.
             
              x = y * 2;
         }
      y = 100; // Error! y not known here


This program will not compile 

class ScopeErr {
          public static void main(String args[]) {
                   int bar = 1; 
                      {
                          // creates a new scope
                                  int bar = 2; //Possible in c++
                         // Compile-time error – bar already defined! 
                       }
              }
}



Type Conversion

// Demonstrate casts.
class Conversion {
 public static void main(String args[]) {
byte b;
int i = 257;
double d = 323.142;
System.out.println("\nConversion of int to byte.");
b = (byte) i;
System.out.println("i and b " + i + " " + b);
System.out.println("\nConversion of double to int.");
i = (int) d;
System.out.println("d and i " + d + " " + i);
System.out.println("\nConversion of double to byte.");
b = (byte) d; System.out.println("d and b " + d + " " + b);
}
}




Type Promotion

byte b = 50;
b = b * 2;  // Error! Cannot assign an int to a byte!


byte b = 50;
b = (byte)(b * 2);//correct value of 100.



Operators

  • Assignment( = )
  • Arithmetic Ex.(+, -, *, /, %)
  • Relational(<, >, <=, >=, ==)
  • Logical(&&, ||, !)
  • Increment and Decrement (++, --)
  • Ternary ( ?: )



Precedence of Java Operator





Refer:


Reactions:

0 comments:

Post a Comment