Primitive Types in Java type size Example value byte 8 bit 5 short 16 bit 10000 int 32 bit 200000 long 64 bit 30000000 float 32 bit 1.1234 double 64 bit 1.23487367 boolean 1 bit (undefined) true or false char 16 bit 'a'
Declaring Variables with Java
Examples
int number;
float weight;
char mycharacter;
You can declare and set the variable
char mycharacter = 'a';
You can assign a different value to variable after declaring with the =
Declaring Variables with Java
Declare variable only once!
int x = 5;
x = 10;
System.out.println(x); // prints 10
This is wrong!
int x = 5;
int x = 10; // Variable already declared!
System.out.println(x);
Final Variable
Final variable is a special variable which value cannot be assigned later
final double PI = 3.14;
PI = 5.0; // Does not work!
Examples
int age, shoeSize;
boolean gender;
char myCharacter = 'k';
double average = 7.7;
TYPE CASTING
Type Casting?
class MyApp {
public static void main(String [] args) {
int a = 5;
short b = a;
System.out.println(b);
}
}
TB308POHJUS-L-2:temp pohjus$ javac MyApp.java
MyApp.java:4: possible loss of precision
found : int
required: short
short b = a;
^
1 error
Solution
class MyApp {
public static void main(String [] args) {
int a = 5;
short b = (short) a;
System.out.println(b);
}
}
Why?
class MyApp {
public static void main(String [] args) {
int a = 5;
long b = 5;
int result = a * b;
System.out.println(result);
}
}
MyApp.java:5: possible loss of precision
found : long
required: int
int result = a * b;
^
1 error
Why?
int a = 5;
long b = 5;
int result = a * b;
int * long -> long!
Example Result of different Calculations Operand Operator Operand Result int + / * - int int long + / * - int, short, long, byte long double + / * - float double double + / * - double double float + / * - float float double + / * - int, short, long, byte double
What is the result?
double a = 5;
int b = 5;
double result = a / b;
double / int -> double
What is the result?
int a = 5;
int b = 5;
double result = a / b;
int / int -> int !!!
Solution
int a = 5;
int b = 5;
double result = (double) a / b;
VISIBILITY OF VARIABLES
What is the problem?
import java.util.Scanner;
class MyApp {
public static void main(String [] args) {
Scanner input = new Scanner(System.in);
int inputVariable;
inputVariable = input.nextInt();
if(inputVariable == 7) {
int myVariable = 80;
}
System.out.println(myVariable);
}
}
TB308POHJUS-L-2:temp pohjus$ javac MyApp.java
MyApp.java:15: cannot find symbol
symbol : variable myVariable
location: class MyApp
System.out.println(myVariable);
^
1 error
TB308POHJUS-L-2:temp pohjus$
Braces and Variable visibility
Variable is visible in it's section(braces) and it's child sections
Variable is not visible outside of it's section.
This works:
int a = 1;
if(true) {
System.out.println(a);
}
This does not:
if(true) {
int b = 1;
}
System.out.println(b);
Braces?
If control statement (if, while, for) contains only one statement you do NOT have to use braces
0 comments
Post a comment