My other sites

Latest News

New Summer Look :)










Java Basic Syntax II

  Looping and Branching Constructs

Arrays in Java

Using Arrays Example

Methods - Functions

Passing Arguments

Example Passing Arguments

The String Object

Using The String Object Example

Converting Strings

Quiz

Exercises
 

 

Looping and Branching Constructs

if-else while [initialization]
if ( boolean-expression )
statement1;
[ else
statement2; ]
while ( boolean-expression ) {
[statements]
[iteration]
}
switch-case for loops
switch ( int-value ) {
case int-value1: break;
case int-value2: break;
default:
}
for ([initialization];
[ boolean-expression ];
[iteration]) {
[statements]
}

Arrays in Java

- Arrays in Java are considered to be objects

- Arrays can contain any simple or complex type

- c++ like declaration : type t[];

- java declaration : type[] t;

- Multidimensional Arrays : type[][]..[] t;

- Subscripts begin at zero

- Out of bounds access throws an Exception


Using Arrays Example

public class InitArrays {
  
public static void main (String[] argv) {
int [] numArray; // declaration numArray = new int[10]; // creation for (int x=0; x<numArray.length; x++) { numArray[x] = x * 2; } for (int x=0; x<numArray.length; x++) { System.out.println("position " + x + " contains: " + numArray[x] ); } } }


Methods - Functions

<modifiers> <return_type> <name> ( <args> ) <block>

modifiers : public, private, protected, static, final

return_type : any type and void for nothing

name : Identifier - Method's name

args : Argument list

block : block of code starting with '{' end finishing with '}'
Examples :

public int getSize();

private byte[] getBuffer();

public void printNums( int[] theArray )
 


Passing Arguments

by Value :

- the argument may not be changed by the method called

- The 8 datatypes are passed this way

by Reference :

- the argument may be manipulated directly by the method called

- Objects are passed this way

What would you do to pass simple datatypes by reference?

complex types by value? For the first case, you can use a wrapper, for the second you need to clone the data first.


Example Passing Arguments

 
public class PassingArguments {

   public void test(int x, int y, int[] array) {
       x=1; y=2; array[0] = 5;
       System.out.println("inside test method x:" + x + " y:" + y + 
                          " array[0]:" +array[0] );
   }

   public static void main(String[] argv) {
      int a = 5; int b = 10 ; 
      int[] ar = {15 };
      System.out.println(
"Before the test call a:"
+ a + " b:" + b + " ar[0]:" +ar[0]); PassingArguments pa = new PassingArguments(); pa.test(a,b, ar); System.out.println(
"After the test call a:" + a + " b:" + b + " ar[0]:" +ar[0]); } }
 

Before the test call:


a:5 b:10 ar[0]:15


inside test method:

x:1 y:2 array[0]:5


After the test call:

a:5 b:10 ar[0]:5

 

The String Object


String, is a container type for 16-bit Unicode chars

Declaration : String str;
Creation : str = new String("hi"); or str = "hi";
Usage : String's methods, operator overloading, String-Number conversions

A String cannot change value after creation

Very frequently used methods:

int length() boolean equals(String)
boolean startsWith(String) String toUpperCase()
String toLowerCase() int indexOf(String)
String subString(int begin) String subString(int begin, int end)
char charAt(int index)  

 

Using String Example

 
public class StringExample { 
   public static void main(String[] argv) {
      String str = new String("my name is Thanassis");
      System.out.println("The string contains:" + str );
      System.out.println("its length is :" + str.length() + " chars");
      System.out.println("uppercase :" + str.toUpperCase());
      System.out.println("lowercase :" + str.toLowerCase());
      System.out.print("-is- starts at :" + str.indexOf("is") );
      if (str.equals("my name is Thanasis")) 
         System.out.println("Yes")
      else System.out.println("No")
   }
}


Converting Strings

- Any simple numeric to String :

1. using String's valueOf(numeric) or

2. using Number Classes and toString()

- String to numeric :

1. using String's intValue() or floatValue() or

2. using Number Classes and parse(String)

 

Quiz


Which of the following statements are correct ?


int i=(int)((a<10) && (b>10));
boolean b = 1;
boolean b = (!!!!(3<4))
System.out.println((char)(260>>2));
int i= (int)(true);
Point $2nd_point = new Point(5,5);


What is the output of the following program?

for (int i=10; i>1; i--) {
for (int j=1; j<10; j++) {
if ( ((i+j)%(10)) == 0 )
System.out.println(i + “ “+ j)
}
}

Exercises


1. Write the HelloWorld program, compile and execute it. After executing successfully, try to alter both the process and the code to get as many errors as possible :) I challenge you. Can you achieve 20 different errors?

2. Write a Java class that declares variables for every available data-type, executes a simple arithmetic operation with each data-type and prints the result. Can you use the “+” operator with all the datatypes?

3. Write a program that creates an array, fills it it with 100 int numbers and finds their average value.

4. Implement a method to reverse a given String

5. Write programs to print :

- the following pattern in all possible directions with the least possible code
*
**
***
****
*****

- the ASCII table ( chars 32-255 )

- the Hypotenuse z of the following right triangle :

Hint! : z = Math.sqrt(double d) returns the square root