Showing posts with label Core Java. Show all posts
Showing posts with label Core Java. Show all posts

Monday, March 1, 2021

Core Lesson 2 : Data Types in Java


So, In this chapter, we would be learning about the various data types available in java and how to declare them, and how to use them in our java program. It is mostly similar to the C and C++ programming languages. Java is a strongly typed language. Every variable has a type, every expression has a type and java always ensures before store data in the variable, do they match the type of variable we have declared.

How to Declare a variable 


Syntax :

datatype var1 [= init_val], var2 = [init_val], . . . ;

The above syntax shows how to declare a variable in java. You can declare one variable in one line and at the end, you have to specify a semicolon. you can declare more than one variable on a single line separated by a comma. you can also initialize their values while declaring them. Let's have a look at the below program which shows different ways by which we can declare and initialize variables.

public class DataTypeDemo {
public static void main(String args[]) {

int singleLineVariable;
int anotherSingleLineVariable=10;
int multipleVariableOnSameLine1, multipleVariableOnSameLine2;
int multipleVariableOnSameLineWithInitValue1= 10, multipleVariableOnSameLineWithInitValue2= 20;
int dynamicallyInitializedVariable = anotherSingleLineVariable * 20;

}
}


Primitive Types

Primitive type refers to a simple type. they represent a single value at a time. unlike complex objects like structure or class. Although java is a completely object-oriented programming language; the exception is for the primitive type. We do have Wrapper classes for each primitive type we will check that out also going ahead in this blog. the reason for keeping primitive types in java is that speeding up the performance of the program. 

Let's have a look at the different simple types available in java

Numeric Data Type

Integer numbers
  • long (range : –9,223,372,036,854,775,808 to 9,223,372,036,854,775,807)
  • int (range : –2,147,483,648 to 2,147,483,647)
  • short (range :–32,768 to 32,767)
  • byte (range : –128 to 127)
Integers are nothing but the Whole numbers in mathematical terms. They represent all signed positive to negative numbers as per their data type. Java does not support unsigned integer types as many other programmings do. Let's have a look at the below example for the Integer declaration

class DataTypeDemo {
public static void main(String args[]) {
byte var1 = 10; // Declaring byte variable with initial value of 10
short var2 = 20; // Declaring short variable with initial value of 20
int var3 = 40; // Declaring int variable with initial value of 40
long var4 = 80; // Declaring long variable with initial value of 80
}
}


Java Also supports Octal, Hexa Decimal, and Binary numbers. Let's have a look at the below program to know how we can declare the integer in the different number system

class DifferentNumberSystems {
public static void main(String args[]) {

// octalNumber value can be declare by leading 0 before number
// blow is the declaration of 10 octal number which is 8
int octalNumber = 010;
System.out.println(octalNumber);

// hexaDecimal value can be declare by leading 0x before the number
// below is the declaration of 0x1A hexa number which is 26
int hexaDecimalNumber = 0x1A;
System.out.println(hexaDecimalNumber);

// binaryNumber value can be declare by leading 0b before the number
// below we have declare binary version of 172
int binaryNumber = 0b10101100;
System.out.println(binaryNumber);

}
}

Floating Point numbers
  • double (64 bit)
  • float (32 bit)

Floating-point numbers represent decimal values with a fractional component. They can be expressed in either standard or scientific notation. Standard notation consists of a whole number component followed by a decimal point followed by a fractional component. For example, 2.0, 3.14159, and 0.6667 represent valid standard-notation floating-point numbers. Scientific notation uses a standard-notation, floating-point number plus a suffix that specifies a power of 10 by which the number is to be multiplied. The exponent is indicated by an E or e followed by a decimal number, which can be positive or negative. Examples include 6.022E23, 314159E–05, and 2e+100.

Floating-point literals in Java default to double precision. To specify a float literal, you must append an F or f to the constant. You can also explicitly specify a double literal by appending a D or d. Doing so is, of course, redundant. The default double type consumes 64 bits of storage, while the smaller float type requires only 32 bits. Let's have a look at below example

public class DataTypeDemo {
public static void main(String args[]) {

// declaring float variable
// Notice f at the end of the number
float var1 = 10.5f;

// declare double variable
double var2 = 3.14;

}
}

Using Separators in the numeric type
  • You must have seen in mathematical books when it comes to defining large number; we use a comma as a separator value
  • This allows the reader to quickly grasp the value of the number by grouping them
  • java allows us to specify separator while you declare the number type values
  • Separator allowed here is underscores character (_)

Let's have a look at the below java example to define a very large number that is easily readable

// Internation format
// one hundred and twenty three million four hundred and fifty six thousand seven hundred and eighty nine
int veryLargeNumber = 123_456_789;

// Indian format
// twelve crore thirty four lakh fifty six thousand and seven hundred and eighty nine
int anotherVeryLargeNumber = 12_34_56_789;

// Value of pi with separator
double fractionalNumber = 3.141_592_653;


Non-Numeric Data Type

Characters
  • In Java, the data type used to store characters is char
  • char in Java is not the same as char in C or C++
  • In C/C++, char is 8 bits wide uses ASCII charset. Instead, Java uses Unicode charset. 
  • Unicode defines a fully international character set that can represent all of the characters found in all human languages. 
  • Unicode required 16 bits. Thus, in Java char is a 16-bit type. 

Let's have a look at the below program that can give you an idea about using characters in java

public class DataTypeDemo {
public static void main(String args[]) {
char firstCharVariable = 'A';
char nextCharVariable = 'B';
char smallCaseLetterVariable = 'h';
}
}

Booleans

  • Java has a primitive type, called boolean, for logical values
  • It can have only one of two possible values, true or false
  • This is the type returned by all relational operators, as in the case of a < b
  • Boolean is mostly used in control execution commands we would be going to learn ahead
  • The values of true and false do not convert into any numerical representation
  • The true literal in Java does not equal 1, nor does the false literal equal 0
Let's have a look at the below example which will demonstrate common usage of boolean

public class DataTypeDemo {
public static void main(String args[]) {

boolean hasVisa = false;
boolean hasJob = true;
boolean isEligibleForVoting = true;

if(isEligibleForVoting) {
System.out.println("Person is eligible for Voting");
}
else {
System.out.println("Person is Not eligible for Voting");
}
}
}

String Data type

String is a Complex data type in java. It is not like the primitive data type. String is a Class in java. String object has a whole bunch of methods available to it. If you have seen the above primitive data type they don't have a method on them which means they are just placeholders to store data on them that can be used for calculation directly. you can not do much on the primitive data type. But String in java is not primitive, you can do a lot of operations on string objects like converting them to lower case, uppercase, concatenate, substring, and so on. We have a separate chapter on String going ahead in this blog.

Let's have a look at the below example of using String data type

public class DataTypeDemo {
public static void main(String args[]) {

String str1 = "Hello this is java program";
String str2 = "This is another line";

String str3 = str1.toUpperCase();

System.out.println(str1);
System.out.println(str2);
System.out.println(str3);
}
}

Important Points to Remember from these lessons

  • We can declare more than 1 variable on the same line of the same data type
  • we can initialize more than 1 variable on the same line of the same data type
  • Java is a strictly typed language. so you cannot assign float to int or float to char
  • We can also initialize number in octal, binary, or hexadecimal format
  • String is not primitive data type. It is a Complex data type in java
  • The primitive variable doesn't have any member function on them
  • Since String is not primitive it has a member function defined inside it


So that All for this Lesson, Let me know if you did not understand anything on this lesson in below comment section, I will try to revert your or I will improve this lesson in this blog.


Till then Good Bye, Happy Coding !!!



Friday, February 26, 2021

Core Lesson 1 : The History and "Hello World" in Java


Java is similar to the C & C++ Language, which is an object originated. most of the functionality of Java is taken from these two languages. Many of Java’s object-oriented features were taken from C++.

The Original motive for Java was not the building computer software or build websites. They wanted to create a language that is platform-independent and could be used for embedded systems in electronic devices, such as TV and remote controls. The problem with C and most other languages were that they are designed to be compiled for a specific architecture. so they need to recompile the program again and again for a different architecture. and many time changes needed in the program to make the execution happen according to the platform. this will turn out to be the platform-dependent code. To overcome this problem they invented java.


Below are the advantage of java 

  • Simple
  • Secure
  • Portable
  • Object-oriented
  • Robust
  • Multithreaded
  • Architecture-neutral
  • High performance


A First Simple Program

Let's take a look at the simple java program below that printout hello world on console

/*
This is Hello World Java Program
Store in the file name HelloWorldJava.java
*/
public class HelloWorldJava {

// Your program execution start from here
public static void main(String args[]) {
System.out.println("Hello World !");
}
}


Compiling the Program

$\> javac HelloWorldJava.java
$\>ll
-rw-r--r-- 1 in-anil.sable 435B Feb 26 21:51 HelloWorldJava.class
-rw-r--r-- 1 in-anil.sable 258B Feb 26 21:50 HelloWorldJava.java


Running the Program

$\> java HelloWorldJava
Hello World !


 A Closer Look at the First Sample Program

/*
This is Hello World Java Program
Store in the file name HelloWorldJava.java
*/

This section in the program represent the Multi Line Comment in the program. these line would be consider as a comments and completely ignore by the Java while compiling the program. We ofter call this as a multi line comment since once can specify many lines withing the pair of /* */


 // Your program execution start from here

This line in the java program represents the Single line Comment. similar to the multiline comment, all the content specified on this line would be ignore by the java while compiling the program. We call it as a single line comment since you can write only 1 line of comment using //. once the line break java treat this as a executable instruction unless new line again start with single line or multi line comment.

Many Developer use the comments to add few details about the method like what is the usage of the method, what kind of parameter we are expecting and what could be the return values. But I personally feel you should avoid adding comments in the program/module unless it is absolutely necessary. I feel your code itself should be so clean that one should not feel the need for comment while reading your code. everything in your program should be self explanatory like name of classes, name of methods and variable name.


public class HelloWorldJava { .... }

The above example uses keyword 'class' to declare the class in java followed by the name of your class. In this example it is 'HelloWorldJava'. You can also see the keyword 'public' which is an access specifier. Dont worry about that now, we would be going to explore all access specifier in java. for now you can just think that this class is Accessiable from other class also. In java programming eveyting like method, variables should be declared inside class only. 


public static void main(String args[]) { .... }

Above line is the declaration on main method. likewise in every other programming language, Application execution start from the main method. This would be the entry point for the the java application. every main method in java should be exactly similar to the above. when we execute the java program, java try to find out the main method in the class, which should be exactly similer to above. talking about the keywords, public is the access specifier which tell the scope of method from which it can get call. since main method is the entry point it should be public so that java can invoke it. We will talk more about the access specifier going ahead in this blog. Static is Non Access specifier, we would talk about this also going ahead in blog, As of now you can think static like, we can Access static things without its object. just by class name. void is return type since this application is not returning anything, we can specify void in its return type


System.out.println("Hello World !");

Result of above line is that whatever is specified in the println("") is getting printed on the terminal. Here System is class inbuilt in java which has out public static variable / data member on which we have println method. System.out by default point out to the output device. in our case it is terminal. There are other data members like System.err, which point out to default error output device and System.in would be default input device, it would be keyboard


An Another Simple Example 

class AnotherSimpleExample {
public static void main(String args[]) {
int firstNumber = 10;
int secondNumber = 15;
int sum = firstNumber + secondNumber;

System.out.println("Sum of numbers is :" + sum);
}
}

Above Example would be little beyond the scope of this lesson, but it will give you the feel of java program. and you can understand how the programs are written in java. By reading each statement you can eaisly understand what this program is doing.


So that All for this Lesson, Let me know if you did not understood anything on this lesson in below comment section, i will try to revert your or i will improve this lesson in this blog.

Till then Good Bye, Happy Coding ! ! !