Characteristics of Java and basic programming constructs like Data types, Variables, Operators, Control Statements, Arrays are discussed with relevant examples
6. DataTypes
Kinds of values that can be stored and manipulated.
Java - StronglyTyped Language
Automatic Widening casting
Boolean: boolean (true or false).
Integers: byte, short, int, long (0, 1, -47)
Floating point numbers: float, double (3.14, 1.0, -2.1)
Characters: char (‘X’, 65)
String: String (“hello”, “example”).
12/1/2020 Vani Kandhasamy,PSG Tech 6
7. 12/1/2020 Vani Kandhasamy,PSG Tech 7
public class Example1 {
public static void main(String[] args) {
int myInt = 9;
double myDouble = myInt; // Automatic casting: int to double
System.out.println(myInt); // Outputs 9
System.out.println(myDouble); // Outputs 9.0
}
}
8. Variables
Named location that stores a value of one particular type.
Syntax: type variable ; (0r) type variable = value;
Example: String rollNo;
rollNo = “19Z30X”;
(or)
String rollNo = “19Z30X”;
12/1/2020 Vani Kandhasamy,PSG Tech 8
9. 12/1/2020 Vani Kandhasamy,PSG Tech 9
class Example2 {
public static void printSquare(int x){
System.out.println("printSquare x = " + x);
x = x * x;
System.out.println("printSquare x = " + x);
}
public static void main(String[] arguments){
int x = 5;
System.out.println("main x = " + x);
printSquare(x);
System.out.println("main x = " + x);
}
}
11. Operators
Symbols that perform simple computations
Type Promotion
Syntax: var = var op expression; (or) var op= expression;
Arithmetic operators: (+, -, *, /, …)
Assignment operators: (=, +=, -=,…)
Relational operators: (==, !=, >, <, …)
Logical operators: (&&, ||, !)
Bitwise operators: (&, |, ~, …)
12/1/2020 Vani Kandhasamy,PSG Tech 11
12. 12/1/2020 Vani Kandhasamy,PSG Tech 12
class Example3 {
public static void main(String args[]) {
byte b = 42;
char c = 'a';
short s = 1024;
int i = 50000;
float f = 5.67f;
double d = .1234;
double result = (f * b) + (i / c) - (d * s);
System.out.println((f * b) + " + " + (i / c) + " - " + (d * s));
System.out.println("result = " + result);
}
}
Output:
238.14 + 515 - 126.3616
result = 626.7784146484375
31. Arrays
Syntax: type var_name[ ] = new type [size];
type[ ] var_name;
Example:
double values[ ] = new double [10]
The index starts at zero and ends at length-1
12/1/2020 Vani Kandhasamy,PSG Tech 31
33. 12/1/2020 Vani Kandhasamy,PSG Tech 36
public class Example7 {
public static void main(String args[]) {
int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int sum = 0;
for(int x =0; x<nums.length; x++){
System.out.println("Value is: " + x);
sum += nums[x];
}
System.out.println("Summation: " + sum);
}
}
34. 12/1/2020 Vani Kandhasamy,PSG Tech 37
public class Example7 {
public static void main(String args[]) {
int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int sum = 0;
// use for-each style for to display and sum the values
for(int x : nums) {
System.out.println("Value is: " + x);
sum += x;
}
System.out.println("Summation: " + sum);
}
}