Java Fundamentals – 2

before refer this post it is expect to refer Java fundamentals – 1 post.

in this article we are going to discuss usage, concepts and best practices about variables and types

Variables

Variable is a container that holds values that are used in a Java program. in other words variable is reserved memory location to store data. Every variable must be declared to use a data type. you need to understand that variable and constant are different. for example

10+2=12 this is constant (not java constant) . because you know answer is always 12
10+k= ???? here answer is unpredictable as its highly depends on the value of “k” meas variable
previous introduction said variable is must declared with type. what is type?

Type

as we learnt variable is reserved memory locations. so operation should know what going to store in order to reserve space. therefore by giving name for certain data you can advice operating system to how much space you required to store data. if you only have numbers it can be int. but if you expect to store characters you need to define type as String.

by the way java is strongly type. that means two things.

  • you need to define data type when you declare variable
  • once you defined you cannot change it

lets write small program to demonstrate variable usage




package com.krishantha.sample;

public class HelloWorld {

public static void main(String[] args) {
 String name="Krishantha";
 
 System.out.println("Hello "+ name);

}

}

Naming variable

lot of developers do not concern about naming variable. too much descriptive name as well as no descriptive vriable name are bad. for example


int x=0; // no descriptive
int studentTotalMarkForTheGivenExam=0; // this also bad as it too much descriptive


so you need to use some mean full name which not break above rule

scope of variable

in simple term scope of variable mean visibility of the variable. varible can have

  • class level scope
  • method level scope
  • block level scope

following diagram will give more clear understanding about scope of variable

variable scope
variable scope

refer below code sample for demonstrate variable scope.

Scope rule demo
Scope rule demo

 

scope rule

variable from super scope is visible to child (inner) scope but variable from child (inner) scope are not visible to super (outer) scope.

block rule

this is irrelevant to variable scope. but variable scope explain thing call “block scope” what is block? in java you can set block for any set of code that treat as single statement. refer following working example


package com.krishantha.sample;

public class HelloWorld {

static int classLevel = 10;

public static void main(String[] args) {

System.out.println("before block " + classLevel);
 
//this is how you can all block
 {
 int classLevel = 20;
 System.out.println("inside block " + classLevel);
 }
 System.out.println("outside block " + classLevel);
 }

}

output will come as follows

before block 10
inside block 20
outside block 10

since “outside block” statement does not have access to value assignment inside block its still has class level assigned value.

Primitive type

What is primitive type is really confused question for beginners. easiest way to answer is non object data types are called as primitive types. if you need more technical answer, when you assign value to primitive type that memory hold exactly what you assigned. while object type variable hold the memory reference.

primitive types and limitations

Integer (4)

byte: The byte data type is an 8-bit signed two’s complement integer. It has a minimum value of -128 and a maximum value of 127 (inclusive). The byte data type can be useful for saving memory in large arrays. They can also be used in place of int where their limits help to clarify your code.
short: The short data type is a 16-bit signed two’s complement integer. It has a minimum value of -32,768 and a maximum value of 32,767 (inclusive).
int: By default, the int data type is a 32-bit signed two’s complement integer, which has a minimum value of -2^31 and a maximum value of 2^31-1. In Java SE 8 and later, you can use the int data type to represent an unsigned 32-bit integer, which has a minimum value of 0 [zero] and a maximum value of 2^32-1.
long: The long data type is a 64-bit two’s complement integer. The signed long has a minimum value of -2^63 and a maximum value of 2^63-1. In Java SE 8 and later, you can use the long data type to represent an unsigned 64-bit long, which has a minimum value of 0 [zero] and a maximum value of 2^64-1.

Floating points (2)

float: The float data type is a single-precision 32-bit IEEE 754 floating point. Its range of values is beyond the scope of this discussion, but is specified in the Floating-Point Types, Formats, and Values section of the Java Language Specification. As with the recommendations for byte and short, use a float (instead of double) if you need to save memory in large arrays of floating point numbers. This data type should never be used for precise values, such as currency. For that, you will need to use the java.math.BigDecimal class instead. Numbers and Strings covers BigDecimal and other useful classes provided by the Java platform.
double: The double data type is a double-precision 64-bit IEEE 754 floating point. Its range of values is beyond the scope of this discussion, but is specified in the Floating-Point Types, Formats, and Values section of the Java Language Specification. For decimal values, this data type is generally the default choice. As mentioned above, this data type should never be used for precise values, such as currency.

Boolean (1)

boolean: The boolean data type has only two possible values: true and false.

Character (1)

char: The char data type is a single 16-bit Unicode character. It has a minimum value of ‘\u0000’ (or 0) and a maximum value of ‘\uffff’ (or 65,535 inclusive).
there is other type call String. not a primitive type but that also treat special which plan to discuss later.

Auto boxing and Unboxing

there are certain containers as well as method which required non primitive data types. means object types. to serve this purpose we have non primitive type belongs to each primitive types. for example int -> Integer or double -> Double. this wrapper act like box. we can put our primitive type to wrapper box and send to destination and when return came can unbox it and get primitive type back. java can handle this automatically. its call Autobox and Autounbox. means when primitive type assigned to its relevant wrapper type you don’t need manually cast and java automatically do that. its call auto boxing.

Operators

I am assuming that you have some kind of programming understanding. therefore i am not willing to explain operators here. you can refer following working example to get an idea about operators


package com.krishantha.samples;

public class OperatorDemo {

public static void main(String[] args) {

System.out.println("source values are 8 and 12\n");
int result = 8 + 12;

//+
System.out.println("Demo \"+\" --> 8 + 12 = " + result);
int original_result = result;

result = result - 1;

System.out.println("Demo \"-\" --> "+original_result + " - 1 = " + result);
original_result = result;

result = result * 2;

System.out.println("Demo \"*\" --> "+original_result + " * 2 = " + result);
original_result = result;

result = result / 2;

System.out.println("Demo \"/\" --> "+original_result + " / 2 = " + result);
original_result = result;

result = result % 7;

System.out.println("Demo \"%\" --> "+original_result + " % 7 = " + result);

original_result=result;
result++;
System.out.println("Demo \"++\" --> "+original_result + "++ = " + result);

original_result=result;
result--;
System.out.println("Demo \"--\" --> "+original_result + "-- = " + result);
}

}

output will comes lile

source values are 8 and 12

Demo “+” –> 8 + 12 = 20
Demo “-” –> 20 – 1 = 19
Demo “*” –> 19 * 2 = 38
Demo “/” –> 38 / 2 = 19
Demo “%” –> 19 % 7 = 5
Demo “++” –> 5++ = 6
Demo “–” –> 6– = 5

Assignment operators

Same as previous paragraph plan to provide working example to understand


package com.krishantha.samples;

public class AssignmentOperators {

public static void main(String[] args){
System.out.println("source value is 12\n");
int result = 12;

//+
System.out.println("Demo \"=\" -->" + result);

int original_result = result;
result += 2;
System.out.println("Demo \"+=\" --> "+original_result + " += 2 -> " + result + " (same as 12+2)");

original_result = result;
result -= 2;
System.out.println("Demo \"-=\" --> "+original_result + " -= 2 -> " + result + " (same as 14-2)");

original_result = result;
result *= 3;
System.out.println("Demo \"*=\" --> "+original_result + " *= 3 -> " + result + " (same as 12*3)");

original_result = result;
result /= 2;
System.out.println("Demo \"/=\" --> "+original_result + " /= 2 -> " + result + " (same as 36/2)");

original_result = result;
result %= 7;
System.out.println("Demo \"%=\" --> "+original_result + " %= 7 -> " + result + " (same as 18%7)");



}
}

output will come as

source value is 12

Demo “=” –>12
Demo “+=” –> 12 += 2 -> 14 (same as 12+2)
Demo “-=” –> 14 -= 2 -> 12 (same as 14-2)
Demo “*=” –> 12 *= 3 -> 36 (same as 12*3)
Demo “/=” –> 36 /= 2 -> 18 (same as 36/2)
Demo “%=” –> 18 %= 7 -> 4 (same as 18%7)

String

it is the most special member in java family. mean special type. String is an object type. however in java its consider something like primitive data type. also string is immutable. immutable means by default its not allowed to change and if you tried to do so it will create new object. also java has provided easy access to string means easy to use. as an example you can create string object without new keyword. (treat like primitive type). however since String is object type it has its own methods such as length() or toUpper() etc

Array

Array may not need to explain in details as its common to almost all programming languages. but still array is the basic concept. however since its cannot re size once created most of the time we use collections rather than arrays

Data Conversion

since we discussed about wide range of data types we need to discuss about how we can convert those to different type.

For example, in a particular situation we may want to treat an integer as a floating point value. impotent point is these conversions are do not change the type of a variable or the value that’s stored in it. they only convert a value. need to be very careful on this as this can lead to loose the information.
Widening conversions are always safe because they tend to go from a small data type to a larger one (such as a short to an int) so there will be enough space.
Narrowing conversions can lose information because they tend to go from a large data type to a smaller one (such as an int to a short)

There are 3 ways to do this

  • assignment
  • promotion
  • casting

Assignment

Assignment conversion means value of one type is assigned to a variable of another. for an example if distance is a float variable and radius is an int variable, the following assignment converts the value in radius to a float
distance = radius
Only widening conversions can happen via assignment. Note that the value or type of radias does not change.


package com.krishantha.samples.conversion;

public class Assignment {

public static void main(String[] args) {
float distance = 123_645_3344;
int radius = 10;

// assignment is valid
distance = radius;

// this is not correct
radius = distance;
}
}

Promotion

Promotion happens automatically when operators in expressions convert their operands
example, if sum is a float and count is an int, the value of count is converted to a floating point value to perform the following calculation:
result = sum / count;


package com.krishantha.samples.conversion;

public class Promotion {

public static void main(String[] args) {

float sum = 123_455_344;
int count = 10;
// promotion
float result = sum / count;

}
}

Casting

this is devil of conversion. means most dangerous one but its very powerfull. Both widening and narrowing conversions can be accomplished by explicitly casting a value. To cast, the type is put in parentheses in front of the value being converted As example, if total and count are integers, but we want a floating point result when dividing them, we can cast total:

result = (float) total / count;

 

Share this on your world...Share on Facebook
Facebook
Share on Google+
Google+
Tweet about this on Twitter
Twitter
Share on LinkedIn
Linkedin
Email this to someone
email
Print this page
Print

Leave a Reply