JAVA BASICS

Java input/output

The Java program shown below is stored in a file named add.java.

import javax.swing.*;
public class add
{ //This program displays a result of an addition
  public static void main(String[] args)
 {
String s;
int n1, n2,sum;
s = JOptionPane.showInputDialog("Enter the first number:");
n1 = Integer.parseInt(s);
s = JOptionPane.showInputDialog("Enter the second number:");
n2 = Integer.parseInt(s);
sum = n1 + n2;
System.out.println(n1 + " + " + n2 + " = " + sum );
JOptionPane.showMessageDialog(null,n1 + " + " + n2 + " = " + sum );
System.exit(0);
 }//end main
}//end class

Run time output
Input


Output

10 + 20 =  30

 


 

                                Analyze the program                                                                     

Note
Double num3;
String s;
S= JOptionPane.showInputDialog(“enter a number”);
Num3=Double.parseDouble (s);

Example:
Algorithm
-         Input 2 integer numbers
-         Calculate the sum
-         Display the input numbers &sum  

import javax.swing.*;       

public class Test

{ public static void main (String [] args)

     String s;                 

            {   int  num1, num2 , sum;

                 s= JOptionPane.showInputDialog(“ENTER THE FIRST NUMBER”);          

num1=Integer.parseInt(s);

s=JOptionPane.showInputDialog(“ENTER THE SECOND NUMBER:”);

num2 = Integer.parseInt(s);

sum=num1+num2;  

            System.out.println(num1);à10

            System.out.println(num2); à20

            System.out.println(“num1”); à num1

            System.out.println( “num1=”+num1); à num1=10

            System.out.println(num1+num2); à30

            System.out.println(sum); à 30

            System.out.println(“num1=”+num1+”\n” + “num2= ”+num2+”\n”+”sum= “ +sum);

                        Output: num1=10

                                    num2=20

                                    sum=30 

            System.out.println(“sum=” + “num1” + “num2”);
                               Output: sum= 10+20
                      
            }
}           

Output to the console window

Examples
System.out.println(“Hello”);
Output
Hello
System.out.println(“ABCD”);
System.out.println("EFG");
Output
ABCD
EFG

Escape Sequences

Use escape sequences in a literal string

Escape Sequences Description
\b Backspace
\t Tab
\n Newline
\f Form feed
\r Carriage return
\" Double quotation marks
\' Single quotation marks
\\ Backslash

Example
System.out.println("He said, \"Hello!\"");
Output
He said, "Hello!"   

Example

System.out.print(“AB\nc”);
Output
AB
C
Example
System.out.print(“AB\nC);
System.out.print(“D”);
Output
AB
CD

Example: to display a double quote, put \ before it.
System.out.print(“AB\”DEF”\”);
Output
AB “DEF”

Character code

ASCII code: 1 byte 
Unicode: 2 bytes
ASCII is a subset of Unicode
Example:
Letter A
Unicode -  Dec: 65  Hex: 0041
Example: display a symbol using unicode

System.out.println(“\u00f4”);
Output
ô

Comment statement

Comment - Code explanation 
Compiler skips the comment statement

Two ways to make comment
-  Use // for one single comment statement
or
-Use /*….*/ for multiple comment statement

Example
import javax.swing.*;
public class Test
{  public static void main (String[]args)
    { // A simple Java displays statement
     System.out.println(“Hello”); //Display “Hello”
     /*Author: Daniel Phan
       CECS 174 */
    }
}

Another Method to input from the keyboard

import java.util.*;
import java.io.*;
public class Test
{
public static void main(String[] args) throws IOException{

//creating an input object of the class Scanner for numeric input
Scanner input = new Scanner (System.in); // System.in is an InputStream
//Create a buffer for string input
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

//declaration of variables
int n1 , n2 = 0;
double n3;
String s;
//Input by the user
System.out.println ("Enter two whole numbers on a line with spaces between them:");
n1 = input.nextInt ();
n2 = input.nextInt ();
System.out.println ("Enter a real number:");
n3 = input.nextDouble();
System.out.println ("Enter a string:");
s = br.readLine();

//Display to the console
System.out.println();
System.out.println ("The sum of those two numbers is " + (n1 + n2));
System.out.println ("number 3: " + n3);
System.out.println ("String s: " + s);
}
}

 

Binary Numbers

Binary number: two digits only 1 or 0
Decimal Number 10 digits  0-9
Hex Number 16 digits 1-15
0-9 and A-F (10-15)

Example
Convert 1010 to decimal number
1010 =  10 1x2^3 + 0x2^2 + 1x2^1 + 0x2^0

101-->  5

Example Convert Hex to Dec

A6 = Ax16^1 + 6 x16^0
10x16 + 6 = 166

40= 4x16^1+ 0x16^0 =64

Values

Integer values
10, 123, 65000, -65 (no comma or decimal point)
Real values
17.5, 162.783, -65.7, 921.46
Character Values encloses in a single character
‘a’ , ‘b’  or  ‘y’
Logical value - True or False
true or false

Example

6 is an integer value
‘6’ is a character Value
‘yn’  is invalid character value
‘\n’ is a valid character value (escape sequence)

Data type

Variables
Variable is a memory location.
Naming a Variable

-         1st character must be a leter a to z

-         OthtersàCombination of numbers and letters

-         Use underscores

-         No special symbols

-         No java keywords (main, public, class….)

-         Case sensitive

Example Naming variables

Valid

Invalid

acb

1abc

A13b

Main

A_b_cd

Ab#df

 

Ab__cd

 

Ab c

Variable declaration

Data type  variable name, variable name, ..;

Example
 int x;
double y, z, r ;
char  choice;
double profit,  int abc; //error
double profit;  int abc; // OK
or
double profit;
int abc;

Declare and intialize a variable

data type variablename=____,variablename=_____

Example       int total =0 , sum =10 ;
                    int x=10 , y; // OK
                    int a, b=20 , c ; //OK
                   double revenue = 6000.0 , int profit =10; //ERROR (need semicolon between 6000.0 and int)

ARITHMETIC OPERATORS

Figure 1.1 lists some common Java operators and their functions.

Figure 1.1 Java Operators
Operator Name Operator Symbol Example Comment
Addition + num1 + num2  
Subtraction - num1 - num2  
Multiplicaton * num1*num2  
Division / 15/3
15.0/2.0
 
Integer division; result is 7; fraction is truncated
Floating-point division; result is 7.500000
Modulus % 5%2 Performs the division and finds the remainder; the result is 1
Unary minus - -(num1) if value of num1 is 10, then -(num1) is -10
Assignment = num1=10; assigns 10 to variable num1
  += num += 10; Equivalent to num = num +10;
  -= num -= 10; Equivalent to num = num -10;
  *= num *= 10; Equivalent to num = num *10;
  /= num /= 10; Equivalent to num = num /10;
  %= num %= 10; Equivalent to num = num %10;
Increment ++ num++ or ++num Increment num to 1
Decrement -- num-- or --num Decrement num to 1

%         a%b à keep remainder (return remainder) apply only to integer data type 

Example:
int x;

x=7%2;

Xß1

Integer division

int x=5, y=z, z;

z=x/y; //zà 2

int a, b=5, c=2;

a=b/c; //a?        a=5/2 =2

double d;

d=b/c; //d?       d=5/2= 2  d --> 2.0

d= b/2.0           d=5/2.0 =2.5  d--> 2.5

a= b/2.0;  //a=?  a=5/2.0 à 2.5

Assignment statement

variable = value, variable or expression

Example
x10; //10=Value
x = y ;//variable
y=x+z; //EXPRESSION

A+b=C; //Invalid (left hand side of the assignment statement is always a variable)

c=a+b; //OK

profit= revenue-expenses //Invalid Java Statement (missing ;)

Convert a math expression to Java statement

F= maà F= m*a; 

A= b+4 /d+f à  a= (b+4)/(d+f); 

A= b+4 /df +g à  a= (b+4) / (d+f) +g ; 

Operator order precedence

Precedence prefers to the order in which the compiler will execute the operations. Operators have different precedences associated with them. Operators also have associativity, which refers to the order in which the compiler will execute operations that have the same precedence. For example, the expression num1 + num2 - num3 includes two operators that have the same precedence--the addition and the subtraction operator. The two operator have left to right associativity, so the computer will begin with the leftmost operator and then move to the right. In this case, the subtraction operator will follow the addition operator. Figure 1.2 shows the precedence and associativity of the operators discussed in this lecture.

Figure 1.2 Order of Precedence
Operator Symbol(s) Order of Precedence Associativity
( ) First Left to Right
- Second Right to Left
* / % Third Left to Right
+ - Fourth Left to Right
=  += -= *= /=  %= Fifth Right to Left

Example
A= 4*2/2+6;
A = 4+2 +2*4 = 6+8 =14
Example:
A= (4*2)/4+6 ;
A = 8/4+6 = 2+6 =8
Example
A= (4+(6*2+4))+10;
A= (4+(12+4))+10 = (4+16)+10 =20+10 =30

UsingMath class

Use the java.lang.Math class to perform a great many math functions.
JAVA math- class has many math methods
-pow(x,y)àx^y
-sqrt(x)à square root x

Use java math method called pow     pow(x,y)àx^y
x and y à double data type

Example
float y;
y = Math.pow(3.0,4.0);
System.out.println( "y = " +  y);
Output
y = 81.0
Example
double x=3, y = 60 , z

z= Math pow (x,y);

Here are some constants and methods of the Math class

Cast operation

You can explicitly override the unifying type imposed by the Java programming language by performing a type cast

               Example:    int x=5;
                                double y;
                                y=(double) x + 1;

Logical Operator

You can use relational operators to construct a relational expressions that compare two values. The result of comparison will be true or false.

Relational Operators
Operator Meaning
< Less than
<= Less than or equal to
> Greater than
>= Greater than or equal to
== Equal to
!= Not equal to

Relational operators

You can use relational operators to construct a relational expressions that compare two values. The result of comparison will be true or false.

Relational Operators in Java
Operator Meaning
< Less than
<= Less than or equal to
> Greater than
>= Greater than or equal to
== Equal to
!= Not equal to

 

Relational expressions

A simple relational expression consists of two operands and one relational operator.
Example:  x > y
                The result of this comparison is true or false value. If the test is true, a value of 1 is returned; otherwise, a value of
                zero is returned.

In Java, the relational expression are not bounded by data type. A relational operator can be used to compare two values of the same data type or the different data type. The operands in a relational expression can include any of the following:

In Java, all boolean values (as true or false sometimes are called) are represented by integers. The value 0 is interpreted as false when it's used with relational or logical operators, and any other integer (positive or negative)   is regarded as true.

          Example:    x = y > 1 + n;
                          In this statement, the variable x would be assigned a value of 0 or 1 depending on whether y is greater than,
                          less than, or equal to 1 + n.

Single alternative decision structure

if STATEMENT 

Syntax Description
if (expression)
{ statementA;}
If the expression evaluates to true, then the computer will execute statementA. If it is false, then the computer will not execute statementA. A Java statement can be either a simple statement or a block statement. A block statement comprises multiple Java statements. Java defines a block as statements placed within curly braces. A simple statement has only one statement.

Pseudocode

if  condition is true then
        true body
endif

Java structure

if ( Condition )
{
       
true Body

}

Notes

Example:
Pseudocode
                                                                     Java

if x is greater than y then                                    if ( x > y )
    display x                                                                   System.out.println(x);
endif

if x is greater than y then                                    if (  x > y )
    z = x + y;                                                          {     z = x + y;
    Display z                                                                System.out.println(z);
endif                                                                     }
Display "Bye"                                                          System.out.println("Bye")

Dual-alternative decision structure

if ... else  STATEMENT

Syntax Description
if (expression)
 {statementA;}
 else
 {statementB;}
If the expression evaluates to true, the the computer will execute statementA. If the expression evaluates to false, then the computer will execute statementB.

Pseudocode

if  condition is true then
        True body
else
        False body
endif

Java structure

if ( Condition )
{
      
true body
}

else
{
      
false body
}

 

Notes

Example:
Pseudocode
                                                                     Java

if x is greater than y then                                    if ( x > y )
    display x                                                                   System.out.println(x);
else                                                                      else
   display y                                                                    System.out.println(y);
endif

if x is greater than y then                                    if (  x > y )
    z = x + y;                                                          {     z = x + y;
    Display z                                                                System.out.println(z);
else                                                                       }
    z = x - y;                                                            else
    Display z                                                           {   z = x - y;
endif                                                                           System.out.println(z);
Display "Bye"                                                     }
                                                                                  System.out.println("Bye");