Programming‎ > ‎Java‎ > ‎

1.Fundamental Programming Structures

A Simple Java Program

  • Java is case sensitive
  • 'public' is access modifier
  • 'class' reminds that everything in a Java program lives inside a class
  • Think 'class' as a container for the program logic that defines the behavior of an application
  • class 'name' must begin with a letter, and after that they can have any combination of letters and digits with unlimited length
  • Source code compilation using javac produces the platform independent bytecode HelloWorld.class
  • When you use java HelloWorld to run the program, the Java interpreter always starts execution with the code in the main method in the class
  • Thus, you must have a main methods in the source file for your class in order for your code to execute
  • The main method in Java is always static
  • Unlike C/C++, the main method does not return an "exit code" to the operating system
  • If the main method exits normally, the Java program has the exit code 0, indicating successful completion
  • To terminate the program with different exit code, use the System.exit method
  • Here System.out object calls the println method, object.method(parameters)

public class HelloWorld 
public static void main(String[] args) 
System.out.println("Hello world!");



  • The most common way is a //
  • Use the /* and */ comment delimiters that let you block off a longer comment. This comment do not nest in Java
  • Third kind of comment that can be used to generate documentation automatically. This comment uses a /** to start and a */ to end

Data Types

  • Java is a strongly typed language. Every variable must have a declared type
  • There are eight primitive types in Java
  • 4 integer types, 2 floating-point number types, 1 character type, 1 is boolean type for truth values


  • int (4 bytes), short (2 bytes), long (8 bytes), byte (1 byte)
  • Under Java, the ranges of the integer types do not depend on the machine on which you will be running the Java code
  • This brings platform and OS independence 
  • Long integer numbers have a suffix L, Hexadecimal numbers have a prefix 0x, Octal numbers have a prefix 0.
  • Java does not have any unsigned types

Floating-Point Types

  • float (4 bytes), double (8 bytes)
  • Numbers of type float have a suffix F
  • Floating-point numbers without an F suffix are of type double, or optionally use suffix D
  • Three special floating-point values - positive infinity, negative infinity, NaN (not a number)
  • Constants Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY, Double.NaN
  • Computing 0/0 or sq root of a negative number yields NaN
  • if (x == Double.NaN) // is never true
  • if (Double.isNaN(x))  // check whether x is "not a number"

Character Type

  • Single quotes are used to denote char constants
  • 'H' is a character, different from "H" string containing a single character 

The boolean Type

  • The boolean type has two values, false and true
  • You cannot convert between integers and boolean values
  • if (x = 0) // oops ... meant x == 0
  • In Java the test does not compile because the integer expression x = 0 cannot be converted to a boolean value


  • In Java, Every variable has a type
  • A variable name must begin with a letter, and must be a sequence of letters or digits
  • Case is significant
  • The length of a variable name is essentially unlimited
  • After variable declaration, you must explicitly initialize it by means of an assignment statement
  • Uninitialized variable usage gives compilation error
  • Variable declaration could be added anywhere in the code
  • In Java, there are no declarations that are separate from definitions


  • In Java, you use the keyword final to denote a constant, value is set once and for all
  • final int count = 2;
  • Class constants are available to all methods inside\outside class using keyword static final
  • public static final int var = 3;


  • The usual arithmetic operators are +-*/
  • There is a convenient shortcut x += 4;
  • Increment Operator ++
  • Decrement Operator --
  • Relational Operator == for equality, != for inequality, <,>,<=,>=
  • Uses && for the logical "and" operator and || for the logical "or" operator, ! is the logical negation operator
  • Java supports the ternary ?: operator condition ? e1 : e2
  • Bitwise perator &("and", | ("or"), ^ ("xor"), ~ ("not")
  • There are also >> and << operators, which shifts a bit pattern to the right or left
  • The right hand side argument of the shift operators is reduced modulo 32, e..g. 1<<35 is same as 1 << 3 or 8

Mathematical Functions and Constants

  • double y = Math.sqrt(x) \\ Math is class, sqrt is static method unlike System.out is object
  • Math.pow, Math.sin, Math.cos, Math.tan, Math.atan, Math.atan2, Math.exp, Math.log
  • Constants Math.PI, Math.E

Conversions Between Numeric Types

  • The legal conversions are
  • byte -> short
  • short -> int
  • char -> int
  • int -> long, float, double
  • long -> float, double
  • float -> double
  • double (no conversion)
  • When combining two values with a binary operator (such as n + fwhere n is an integer and f is a floating-point value), both operands are converted to a common type before the operation is carried out
  • If any of the operands is of type double, the other one will be converted to a double
  • Otherwise, if any of the operands is of type float, the other one will be converted to a float
  • Otherwise, if any of the operands is of type long, the other one will be converted to a long
  • Otherwise, both operands will be converted to an int


  • double x = 9.997; int nx = (int) x
  • The variable nx has the value 9, as casting floating point value to an integre discards the fractional part
  • int nx = (int) Math.round(x);
  • Use Math.round to round floating point number to nearest integer. You still need cast (int) with round as return value is long and long can only assigned to int by explicit cast with possibility of information loss


  • Strings are sequence of characters, such as "Hello".
  • Java does not have built-in string type. Standard Java library has String class
  • String e = "";  // an empty string
  • String greeting = "Hello";


  • + sign to join (concatenate) two strings
  • When you concatenate a string with a value that is not a string, the latter is converted to a string


  • substring method is the String class
  • String s = greeting.substring(0,4); // Hell , (4-0) = 4 characters

String Editing

  • int n = greeting.length();  // is 5
  • char last = greeting.charAt(4) // fourth is 'o'
  • The String class has no methods that let you change a character in an existing string. However you take substring and concatenate.
  • greeting = greeting.substring(0, 4) + "!";
  • Object of String class is immutable with advantage that the compiler can arrange that strings are shared
  • Suppose strings are sitting in common pool. String variables then point to locations in the pool.
  • If you copy a string variable, both the original and the copy share the same characters.
  • Overall, the designers of Java decided that the efficiency of sharing outweighs the inefficiency of string editing by extracting substrings and concatenating.
  • Use StringBuffer class for direct manipulation of strings for efficiency
  • Java String is analogous to a char* pointer rather than char [] in C programming
  • C++ strings are mutable - you can modify individual characters in a string

Testing Strings for Equality

  • s.equals(t) or "Hello".equals(command) i.e. string variable or string constant
  • "Hello".equalsTgnoreCase("hello")
  • Do not use the == operator to test strings for equality. It only determines whether or not the strings are stored in the same location.
  • If the Java virtual machine would always arrange for equal strings to be shared, then you could use == for testing equality. However, it is not a good practice.
  • String functions 

Control Flow

Block Scope

  • Blocks define the scope of your variables
  • Blocks can be nested inside another
public static void main(String[] args)
  int n;
     int k;
     int n; // error -- can't redefine n in inner block
  } // k is only defined up to here

  • However, it is not possible to declare identically named variables in two nested blocks.

Conditional Statement

  • if (condition) { statement }
  • if (condition) { statement1 } else { statement2}

Indeterminate Loops

  • while (condition) { statement }  // condition executed before execution
  • do  { statement } while (condition);  // condition executed after execution

Determinate Loops

  • for (statement1; expression1; expression2) { statement2 }
  • statement1 is counter initialization
  • expression1 is condition which is tested before each pass of for loop
  • expression2 is update the counter
  • Switch Statement - case labels must be integers, you cannot test string in choice
  • The continue statement transfers control to the header of the innermost enclosing loop
  • If the continue statement is used in for loop, it jumps to the "update" part of the for loop
int choice = 10;
switch (choice)
  case 1:



  • An array is a data structure that stores a collection of values of the same type
  • You can access individual value through an integer index
  • Declaration of array int[] a; or int a[];
  • Definition or creation of array int[] a = new int[100];
  • Length of array arrayName.length
  • Array size can't be changed after creation, for expanding array use array list
  • Array initialization
  • smallPrimes = new int[] (17, 19);
  • int[] anonymous = (17, 19);
  • It is legal to have arrays of length 0. These are used for method that computes an array result and result is empty
  • new elementType[0]
  • The element of length 0 is not same as null

Copying Arrays

  • You can copy one array variable into another, but then both variables refer to the same array
  • int[] luckyNumbers = smallPrimes;
  • luckyNumbers[5] = 12; //smallPrimes[5] is also 12
  • System.arraycopy(from, fromIndex, to, toIndex, count);

Sorting an Array

  • Array.sort(a); // Uses tuned version of QuickSort algorithm

Multidimensional Arrays - Ragges Arrays

  • double[][] balance = new double[NYEARS][NRATES];
// First allocate the array holding the rows

int[][] balance = new double[NYEARS][];

// Next allocate the rows
for (int n = 0l n < NYEARS; n++)
  balance[n] = new double[NRATES];

for (int i = 0; i < balance.length; i++)
  for (int j = 0; j < balance[i].length ; j++)

  • Java has no multidimensional arrays at all, only one dimensional arrays
  • Multidimensional arrays are fakes as "arrays of arrays" 
  • Arrays in which different rows have different length are ragged arrays