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

Wednesday, August 12, 2020

[Interview Question ][Data Structure] Two Sum Problem -Array

Two sum problem is one of the most asked data structure questions for a java developer interview. There could be one or more ways to solve the problem but i am trying to give the optimized solution to this problem.

Image


Lets first see the Problem Statement.

Problem Statement - Given an array, We need to find all the possible sets of 2 elements whose sum is equal to the target sum.


Solution: Given an array, lets say [10,-2,5,3,1,7,4] and given a target = 8 , We need to find all the possible 2 elements whose sum is equal to the 8.

the possible output will be 

[10,-2] ,[5,3],[1,7]


Pseudo code- 

  • Lets first sort the array.
  • After sorting, take 2 pointers, one is leftmost & second is rightmost.
  • we will start taking each element from left & right then check some of both the element.
  • If the sum is less then the target sum, then move the left pointer by one.
  • if the sum is greater than the target sum, then move the right pointer to left by one.
  • else if it is equal to target then put the elements one result array and move both left & right pointer by one.
Now let see the Java implementations.






public class TwoSumProblem {
	
	public static void main(String[] args) {
		int[] arr = {10,-2,5,3,1,7,4};
		
		twoSumArray(arr,8);
	}
	
	public static void twoSumArray(int[] arr, int i) {
		
//		sort the array using Arrays  sort
		
		Arrays.sort(arr);
		int size = arr.length;
		int left = 0;
		int right =size-1;
		List<Integer> list = new ArrayList<Integer>();
		
		while(left<right) {
			int diff = arr[left]+arr[right];
			if(diff<i) {
				left++;
			}else if(diff>i) {
				right--;
			}else {
				list.add(arr[left]);
				list.add(arr[right]);
				left++;
				right--;
			}
		}
		
		for(Integer it : list) {
			System.out.println(it);
		}
	}


If you run this program you will get the list of sub set whose sume is equal to 8.


Hope this will help you in your datastructre problem solving.

Thanks for reading.

Thursday, June 25, 2020

[Multi threading Interview Question ]Rate Limiter Implementation in java

There was one interesting problem I have encounter while preparing for a multithreading coding interview.
Image


Question: We have an application for which we need to implement RateLimiter, 
Rate Limiter is an interface which will play a role to limit the number of Request client send to Server in a given time.

In the Current Question, it was asked to implement a rate limit who will do 2 things.

1) It will only allow one client to send 100 requests in 1 hrs. ( one client will be identified by the client Id).
2) It will allow a total of 10000 requests to be passed to the server in 1 hrs.

Rate Limiter Interface 
interface RateLimiter{

boolean accept(String clientId);
}

Java Implementation of Rate Limiter 

When we need to Implement such things where there is any restriction of accessing the resource for limited count We always start thinking using Semaphores  
Why Semaphores? 
Because it maintains the multi-access locking on its own with defined number of threads to access the critical section.

MyRateLimiter.java

class MyRateLimiter  {
 
 
    private Semaphore semaphore;
    private int maxPermits;
    private TimeUnit timePeriod;
    private ScheduledExecutorService scheduler;
    
    
 
    public static MyRateLimiter create(int permits, TimeUnit timePeriod) {
    MyRateLimiter limiter = new MyRateLimiter(permits, timePeriod);
        limiter.schedulePermit();
        return limiter;
    }
 
    private MyRateLimiter(int permits, TimeUnit timePeriod) {
        this.semaphore = new Semaphore(permits);
        this.maxPermits = permits;
        this.timePeriod = timePeriod;
    }
 
    public boolean tryAcquire() {
        return semaphore.tryAcquire();
    }
 
    public void stop() {
        scheduler.shutdownNow();
    }
 
    public void schedulePermit() {
        scheduler = Executors.newScheduledThreadPool(1);
        scheduler.scheduleAtFixedRate(() -> {
            semaphore.release(maxPermits - semaphore.availablePermits());
        }, 0, 1, timePeriod);
 
    }

 }

 RateLimiterImpl.java

	class RateLimiterImpl implements RateLimiter{

private static long MINUTE_TIME_LIMIT=1000*60L; // update as per question
private static long REQUEST_ALLOWED_PER_MINUTE=10000; // Update as per question
Queue<Long> q = new LinkedList<>();
private static int minuteLimit=100;

private Map<String, Optional<MyRateLimiter>> limiters = new ConcurrentHashMap<>();
     
@Override
public boolean accept(String clientId) {
if(!hit(System.currentTimeMillis())) {
return false;
}
Optional<MyRateLimiter> rateLimiter = getRateLimiter(clientId);
if(rateLimiter.isPresent()) {
boolean canAcquire= rateLimiter.get().tryAcquire();
if(canAcquire)
return q.add(System.currentTimeMillis());
}
return false;
}
private boolean hit(long timestamp) {
while(!q.isEmpty() && timestamp-q.peek() >= MINUTE_TIME_LIMIT) q.poll();
if(q.size() < REQUEST_ALLOWED_PER_MINUTE)
{
q.offer(timestamp); 
return true;
}
return false;
}
private Optional<MyRateLimiter> getRateLimiter(String clientId) {
        return limiters.computeIfAbsent(clientId, id -> {
            return Optional.of(createRateLimiter(id));
            
        });
    }
private MyRateLimiter createRateLimiter(String clientId) {
        return MyRateLimiter.create(minuteLimit, TimeUnit.MINUTES);
    }

}

Main Class Calling

public class RateLimiterDemo {


public static void main(String[] args) {

RateLimiter limiter = new RateLimiterImpl();
        System.out.println("test1 " + limiter.accept("test1"));
        System.out.println("test1 " +limiter.accept("test1"));
        System.out.println("test1 " +limiter.accept("test1"));
        System.out.println("test1 " +limiter.accept("test1"));
        System.out.println("test2 " +limiter.accept("test2"));
        System.out.println("test2 " +limiter.accept("test2"));
        System.out.println("test2 " +limiter.accept("test2"));
        System.out.println("test2 " +limiter.accept("test2"));
        System.out.println("test1 " +limiter.accept("test1"));


}

}

You can also check the Code from HERE 

Hope this will help you in understanding the Code

Sunday, September 2, 2018

Remote Debugging of Java Application deployed on AWS Elastic Beanstalk

Most of the time we stuck in the situation where we need to do remote debugging of the application which is running on some server or somewhere other than localhost. We need to debug the code in eclipse. To do that we need to allow the running application to allow remote debugging. 

Image

Generally, we know how to do remote debug in eclipse while the code is running on tomcat. In this post, we will see how to do remote debug when the application is deployed over AWS by elastic beanstalk.



Let's start.

To do Remote debug of AWS deployed the application, we need to follow below steps.

1)We need to Go to AWS Console -> Elastic Beanstalk -> Application -> Configuration
Image

2) Under Configuration you need to go to Software ->Modify ->Container Options 
 Now in Container Options, search for JVM options    In this text box you need to write the below arguments.
-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=5005
Now, these arguments say that - The remote debug will be listening at 5005 port.

3) Now you need to Go to EC2 Instance running from AWS Console -> EC2

4) After that you need to check which security group is defined for that EC2 Instance, you need to allow this port to communicate outside AWS.

5)For that, you need to add the Port in Inbound and Outbound of the Security Group
   Select the Custom Protocol and define the Port as 5005 and then define Anywhere in Ip accessible.

After this, you will be able to communicate the port with the local debugger of the eclipse.

Now you need to configure the Local Eclipse environment for Remote debugging.


Configure Local Eclipse 


For this you need to go to  Run ->Debug Configuration -> Remote debugging 

Under that define the IP of the application ( you need to find the IP of the application at EC2 Instance Properties )

Define the port as 5005 ( as defined above).

Run the application and hurray, are now connected with the AWS application running.

Now you will be able to debug remotely.

Hope you like the post, If so please share it with your friends and family.

Thanks for reading
Noeik

Wednesday, March 21, 2018

Arrays in java

Image
Another pretty important component in Java programming is the use of Arrays. Like variables and loops, most of the program you will write will make use of them.
An Array can be defined as an data type that holds a collection of of a similar data type. with having consecutive memory allocation.




Before more further let see previous post of series
  1. Making Games With Java- Introduction
  2. Getting Everything you need for Java
  3. Introduction to Java Programming
  4. Basic data types and Variables in java
  5. Basic Data types and Variables in java - Continued...
  6. User Input using Scanner class in java
  7. Conditional Logic in java
  8. Loops in java

What are arrays used for?

There are two main uses of arrays:
  •     Conecutive Memory Allocation
  •     Easy Data access ( as index fetch )
Now consider this: you have to create the programme that finds the average age of thirty people. You can do this in two ways. You could:
  1. Create 30 separate age variables (age1, age2… age30) and define values for each of them one by one, before actually calculating the average. This is very inefficient, tedious, and will make the code unnecessarily lengthy.
  2. Or you could store all thirty age values into a single Integer array, which you could call something like ‘Age’. Not only will this be less stressful, it also makes it easier to access data through the array index.
Arrays in Java are index-based i.e. elements stored in array are accessed through their index values. And array indices also start from 0. Therefore, the first element is stored at 0, the second at 1, etc.
Image
Is there a con to arrays?
  • The major disadvantage to arrays is that they can only contain a fixed number of elements, which cannot be changed at runtime.
  • You need to declare the size of the array at the compile time only.
Declaring Arrays.
Array and variable declaration have the same basic principle. You state the data type you want to use with the array (int, char, float, etc.), you give the array a name and save the value into it. The main difference is the addition of square brackets ([]), which is basically the universal coding symbol for arrays.
Below, I have created an integer array variable named arrayInt:
int arrayInt [] ;
You can see that it looks like a basic integer variable, with the addition of the square brackets to the end of variable name.
Note, the square bracket can be added to the back of the data type instead of the variable name, like so this is also valid declaration.
int [] arrayInt ;

Also take note that in the naming of arrays, the rules that apply to naming of variables apply. If you’re not sure what they are, please click this link. You can also turn any data type into an array. You can create a String array:
String arrayString [];
… a Float array:
float arrayFloat [];
… and even a Boolean array:
boolean arrayBool [];
But we don’t know how many values can be saved into the arrays yet. To set this, in the integer array for example, go to the next line and type this in:
arrayInt = new int [5];
According to the code above, this array has a limit of five values. It will not accept or recognise any more values after the fifth.
You can also declare the array limit on the same line where you declared the array:
int[] arrayInt = new int[5];
So now we’ve created an integer array called ‘arrayInt’, that can hold up to five integer values.  Now that we’ve set the array, the system will assign default values of zero to all array positions.
Now, assign values 1 to 5 in each array position:
arrayInt [0] = 1;
arrayInt [1] = 2;
arrayInt[2] = 3;
arrayInt[3] = 4
arrayInt[4] = 5;    
System.out.println(arrayInt[2]); 
Now, we’ve assigned values to each and every memory space in the array, and we’ve set a print statement to print out the third value (the value with the memory space [2]. The code in your coding window should look a lot like this:
Now run your programme, it means your output was this:
Image
But if you’re like me, and would rather do everything one line, you could just as well do this:
int [] arrayInt = {1, 2, 3, 4, 5};
Note, you don’t have to specify the number in the square bracket. The number of values you set will automatically be the set as the array limit.
You probably also noticed that you no longer needed to use the new keyword, or repeat the data type, or put another square bracket. Let me warn that this will only work in the case of int, String and char values. You can do this:
char [] arrayChar = {'A', 'B', 'C', 'D'};
…or this:
String [] arrayString = {"My", "name", "is", "Vishal"};
But not this:
boolean [] arrayBool = {true, false, false, true};
For that, you’d have to do this:
Boolean [] arrayBool = new Boolean [] {true, false, false, true};

Arrays and Loops

If there’s anything that arrays work well with, it’s loops. In fact, any program that uses arrays would most likely make use of loops, and loops can also be used interchangeably with arrays.
Let’s take the integer array we made earlier and join it with a loop. Remove the print statement and replace it with this for loop:
for(int i = 0; i < arrayInt.length; i++){
    System.out.println(arrayInt[i]);
}
Run it and it will count every number in the integer array, from 1 to 5, like this:
Image
Another thing you can do with loops and array is use a loop to set values to your array. I mean, in the beginning, I said that we could assign values to the array by doing this:
arrayInt[2] = 3;
But this would be tedious for assigning values to, let’s say, thirty values or more. Like now, instead of just typing a long list of variables and values repetitively, we could just as easily use a loop. Comment out everything you’ve done so far and type this down:
int[] arrayInt = new int[30];
for(int i = 0; i < arrayInt.length; i++){
arrayInt[i] = i + 1;
System.out.println(arrayInt[i]);
}
Then run it, and your result should be this:
Image
I enlarged my output table to show all the values. You can do this by holding your cursor over the output window until you see the arrow pointing up and down, then drag up.
Multi-Dimensional Arrays
So far, the arrays we’ve been looking at are one-dimensional (they can only take one column of data). But you can set up arrays that hold data in rows and columns; kind of like a matrix.
These arrays are called Multi-Dimensional Arrays. They are declared the same way as one-dimensional arrays, except they have two square brackets instead of one:
int [] [] arrayInt = new int [4] [4];
The first square bracket shows the number of rows in the array while the second shows the number of columns. 
The above array has four rows and four columns.

Assigning values to Multi-Dimensional Arrays
To assign values to a multi-dimensional array, you must specify the row and column numbers you want the value to be saved in. For instance:
arrayInt [0][0] = 1;
arrayInt[0][1] = 2;
arrayInt[0][2] = 3;
arrayInt[0][3] = 4;
The first row is 0, so every value is assigned to that row. 
The columns count from 0 to 3, which is four values. To fill the second row, you would have to change the value in the first brackets from 0 to 1, leaving the column values the same.
Continue adding values until you’ve filled every row and column. When you’re done, you should have something like this:
Image
Now normally, before we printed out every value in an array, we would use a for loop. That is the same case in multi-dimensional array, except in this case, you’ll need two for loops. One for the rows, and the other for columns.
Quickly add these lines to your code:
Image
So, the two loops are set to run until their values reach the limits of our rows and columns, printing out our values as thus:
Image

Now if we see the full Program of array 


package tutorialproject;


public class Arrays {

   
    public static void main(String[] args) {
        int[][] arrayInt = new int [4][4];
        
            arrayInt[0][0] = 1;
            arrayInt[0][1] = 2;
            arrayInt[0][2] = 3;
            arrayInt[0][3] = 4;

            arrayInt[1][0] = 5;
            arrayInt[1][1] = 6;
            arrayInt[1][2] = 7;
            arrayInt[1][3] = 8;
            
            arrayInt[2][0] = 9;
            arrayInt[2][1] = 10;
            arrayInt[2][2] = 11;
            arrayInt[2][3] = 12;
            
            arrayInt[3][0] = 13;
            arrayInt[3][1] = 14;
            arrayInt[3][2] = 15;
            arrayInt[3][3] = 16;
            
            int rows = 4;
            int columns = 4;
            int i, j;
            
            for(i = 0; i < rows; i++){
                for(j = 0; j < columns; j++){
                    System.out.print(arrayInt[i][j] + " ");
                }
            }
            
            System.out.println();
        }
        
    }

I hope you have learned something in this post , if you liked it please share it with your friends and colleagues ,

Happy learning
Noeik

Tuesday, March 20, 2018

Program of Rotating 2D Array in java

Image

Objective : We will be given one 2D array we need to rotate the array by 90 degree or by given degree.



There can be 2 type of implementation we can do for this problem solution

  1. Novice Solution , we will create one array and fill the array according to the degree provided.
  2. In Place Rotation in which we will change the value in same array only.

Implementation : Using Temp Array for Rotation:

public class R2 {
    public static void main(String[] args) {
        // NOTE: The following input values will be used for testing your solution.
        int a1[][] = {{1, 2, 3},
                      {4, 5, 6},
                      {7, 8, 9}};
        // rotate(a1, 3) should return:
        // [[7, 4, 1],
        //  [8, 5, 2],
        //  [9, 6, 3]]

        int a2[][] = {{1, 2, 3, 4},
                      {5, 6, 7, 8},
                      {9, 10, 11, 12},
                      {13, 14, 15, 16}};
        // rotate(a2, 4) should return:
        // [[13, 9, 5, 1],
        //  [14, 10, 6, 2],
        //  [15, 11, 7, 3],
        //  [16, 12, 8, 4]]
    }

    // Implement your solution below.
    public static int[][] rotate(int[][] a, int n) {
        int[][] rotated = new int[n][n];
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                rotated[j][n - 1 - i] = a[i][j];
            }
        }
        return rotated;
    }
 }


The Space Complexity of this approach is higher than the new approach , Let see the new Approach.




Second Way : Using Inplace Rotation way

public class R2InPlace {
    public static void main(String[] args) {
        // NOTE: The following input values will be used for testing your solution.
        int a1[][] = {{1, 2, 3},
                      {4, 5, 6},
                      {7, 8, 9}};
        // rotate(a1, 3) should return:
        // [[7, 4, 1],
        //  [8, 5, 2],
        //  [9, 6, 3]]

        int a2[][] = {{1, 2, 3, 4},
                      {5, 6, 7, 8},
                      {9, 10, 11, 12},
                      {13, 14, 15, 16}};
        // rotate(a2, 4) should return:
        // [[13, 9, 5, 1],
        //  [14, 10, 6, 2],
        //  [15, 11, 7, 3],
        //  [16, 12, 8, 4]]
    }

    // Implement your solution below.
    public static int[][] rotate(int[][] a, int n) {
        // n/2 gives us floor(n/2)
        // and n/2 + n%2 gives us ceiling(n/2)
        for (int i = 0; i < n / 2 + n % 2; i++) {
            for (int j = 0; j < n / 2; j++) {
                int[] tmp = new int[4];
                int currentI = i;
                int currentJ = j;
                for (int k = 0; k < 4; k++) {
                    tmp[k] = a[currentI][currentJ];
                    int[] newCoordinates = rotateSub(currentI, currentJ, n);
                    currentI = newCoordinates[0]; currentJ = newCoordinates[1];
                }
                for (int k = 0; k < 4; k++) {
                    a[currentI][currentJ] = tmp[(k + 3) % 4];
                    int[] newCoordinates = rotateSub(currentI, currentJ, n);
                    currentI = newCoordinates[0]; currentJ = newCoordinates[1];
                }
            }
        }
        return a;
    }

    public static int[] rotateSub(int i, int j, int n) {
        int[] newCoordinates = new int[2];
        newCoordinates[0] = j;
        newCoordinates[1] = n - 1 - i;
        return newCoordinates;
    }
 }

I hope this will help you in solving the problem, If you like this post , please share with your friends and colleagues.

Thanks for reading
Noeik 

Thursday, March 1, 2018

Top 5 Free IDE for Java Development & Programming

Image

IDE  is one of the basic fundamental necessity of any programming  why because without it you cant even think of building any application now a day if you are very new to java programming , you probably using notepad or notepad++ for writing you hello world program but have you every think how programming will be happened in IT Industry , do the programmer write the code in notepad or notepad++ only.
Also see Top 5 Courses for Java / Spring developers



Let see what IT industry or even and individual Programmer use for Java programming .
IDE Integrated development environment is software which provide all the facilities a programmer required to develop the application. So what all IDE programmer used for java programming.


Let see the Top 5 IDE used for java programming.

  • Eclipse : Eclipse is one of the Best Open source IDE used for Java development in IT Industry , It is completely free as well as provide great integration functionality to third party plugin such as git , maven etc.  Eclipse is one of the Widely used IDE for Java development.
      • It is maintained by open source community Eclipse Foundation
      • Latest Version of Eclipse – Eclipse Oxygen
      • Download it from here 

  • Intellij IDEA : It is one of the best Open Source IDE not only for Java development but for everything else , It is mostly used for Front end development , The Best thing of IntellijIDEA is it is as licensed IDE as well as Community Version IDE , So you will get the Enterprise support as well if you required.
      • It is maintained by JetBrains
      • Latest version : 2017.3 Build: 173.3727.127
      • Download from here

  • Netbeans: Netbeans is also very popular for java development , It is mainly used for Desktop Application as it provide the functionality of Drag and drop for desktop application.

  • BlueJ is an integrated development environment (IDE) for the Java programming language. It has been mainly developed for educational purposes, but is also suitable for those who wish to do small-scale software development. It runs with the help of a JDK (Java Development Kit).
      • It is maintained by BlueJ Team
      • Latest Version : 4.1.2
      • Download it from here 

  • Android Studio : Android Studio is one of the best for Mobile developers especially Android Developer , Though Android written upon wrapper of Java. Android Studio is freely available under the Apache License 2.0 and it is available for download on Windows, Mac OS X and Linux and replaced Eclipse as Google’s primary IDE for native Android application development.
If you have any other IDEs which are better than mentioned above you can leave us a comment stating your opinion.

Thanks for reading
Noeik

Wednesday, February 28, 2018

Basic data types and Variables in java

Basic data types and variables are the building block of any programming language , and java is also one of them .Welcome back, dear readers. I know what you’re all thinking: “Yeah, finally I wrote my first code! Woo hoo!”. Then eventually you’ll start thinking: “Wait, that’s Javaprogramming? How do use that that to make cool apps and games?”. At least that’s what I thought when I started. I know that doesn’t look like much now, but don’t worry, that was just an intro. We’ll do way more as we go along.
Image

Before We more further , below are the previous post link of the seires
Keep in mind that the more we learn, the harder it gets. I’ll be happy to teach you a lot on programming, but for it to really stick, you’ll need to build on what you learn here for it to stick. By that I mean doing a lot of practicing and experimentation Sometimes the best way to know what to do, is to find out what not to do.
So let’s get started.

VARIABLES

Now, programs work by manipulating data that is being inputted and stored in the computer. This data can be numbers, texts, objects, lists, links to other memory areas and so on. The data is given a name, so that it can be recalled whenever it is needed. The name and data type is called a variable.
You can think of variables like a box. If I have a box, or variable, for storing food, and I call it my Fridge (because it’s obviously a fridge), then I can put stuff like milk, cheese and baloney into my fridge (because variables are variable, they can easily be reassigned new values). So in a way you can say the data type is box, the variable name is Fridge, and the data stored is, let’s say, milk.
Now the standard format for assigning variables in Java (and most other languages) is this:
(Data Type) (Variable Name) = (Data to be stored);
So using this logic, this s how we put stuff in our fridge:
box Fridge = Milk;
(Never forget the semicolons!)

See also Top 10 Interview Questions

Now like most things, the assignment of variables also has its rules (and for all rebels reading this, these rules are NOT made to be broken), especially in regards to naming your variables:
  • RULE 1: Variable names cannot begin with numbers or symbols, letters only. Basically, you can’t have a variable named “2wo” or “$ign” or anything like that. Of course, variables can contain numbers and symbols, just not in the beginning.

  • RULE 2: There can be no spacing in variable names (i.e. nothing like “Number of People). If you want to name a variable that, it’s best to delete the blank spaces (NumberOfPeople) or use the infamous underscore (Number_Of_People_).
  • RULE 3: You can’t use a variable name that also happens to be a java keyword, e.g. if the word “String” is a keyword, you can’t make the variable name “String”. You could call it “FirstString” though.
  • RULE 4: Variable names are very case sensitive i.e. “FirstString” and “firstString” are two completely different variables. Also if you make the mistake of typing “FistString” when assigning the variable, then you type “FirstString” later in the code, it will give an error.
  • RULE 5: This isn’t actually a rule, since you don’t have to do this, but in respect to rule 2, it’s common practice to start the first word with a small letter and the second with capital e.g. “firstString” instead of “FirstString”. Again, they’re both correct, but the first one is just better programming practice.

Now let’s look at some basic data types.



INTEGER VARIABLES-


Launch NetBeans, and open the TutorialProject file from the last tutorial. Without deleting the code, we wrote last time, type in this:

Image

Now, the ‘int’ there is an integer which is a data type that stores whole numbers. To assign a number, go to the next line and type this.

int firstNumber;

        firstNumber = 20;

Or, you could directly assign the variable like this:

int firstNumber = 20;

You’ll see a grey line under the variable name. This isn’t an error message, so don’t worry, it’s just the system remind you that you haven’t called your variable. Place your cursor over the line and you should see the message. If the line just disturbs, don’t worry, we’ll remedy that in a second.
If you hadn’t deleted the print line we made, delete the “Hello World” and type in “firstNumber”, this time without quotes (because this time it’s actually code). If you run it, you will most definitely see this.
Image

Change the number in the code and try it out, you’ll definitely see the exact same number. Now let’s try something a bit different, change your ‘println’ statement to this:
System.out.println(“The first number is” + firstNumber);

The plus means you should join the message in quotes to the value stored in the variable. This is known in programming as a concatenation.
Run your programme and look at the output. Can you see what’s wrong?

Image

You guessed it! There’s no space between the ‘is’ and the ‘20’. This is because the quotation marks read the message as a string, including the spaces. To fix this, put a space after the ‘is’ in the code, so that it’ll look like this:
System.out.println(“The first number is ” + firstNumber);
Run it, and it should look much better.
Now a variable is just a memory space, so it has a limit to what can be assigned to it. An integer value, for example, can only take numbers between −2147483648 and 2147483648. If you want values larger or smaller than that, you can use the double variable.


DOUBLE VARIABLES

Doubles store much larger values than integers with the maximum and minimum at 17 with about 307 zeroes. It is also used to store floating point values (floating point is a fancy word for decimal value) e.g. 8.2, 3.12, 41.5, etc.
Let’s see them at work. Under the integer variable you’ve made, type this down:
double firstDouble = 20.8;
Then in the print function, change “firstNumber” to “firstDouble” and run it:
Image
If you’re curious as to what happens if you put a decimal value in an integer, add .8 to the 20 in the integer variable and put it in the print statement, or better yet, change the double variable to int. Then just run it. You should see an error, and then you’ll know what happens.


FLOAT VARIABLES

These are very similar with doubles, since they also store floating point values (as their name implies). The main difference between the two is that the double has more memory space than the float, and so can store more values (the Double is 64 bits while the Float is 32 bits).
Another difference is the way values are assigned in Floats. Besides the change in data type name (from double to float), there is also an addition of the letter ‘f’ to the back of the value, i.e.
float firstFloat = 20.9f;
Type this in and run it. (It won’t show the f in the result). This should be your output:
Image

Try removing the f and see what happens.
There are other data types like short, long, Boolean, string, char, etc. but for the purpose of this tutorial, we’ll stick with these three. The others will be brought forth and explained as time comes.

ARITHMETIC OPERATORS

Now in the world today, a world of games and social media and entertainment and artificial intelligence, we sometimes forget what computers actually are: oversized calculators! It sounds weird but it’s true. The original computers were built to perform basic calculations, and it’s actually through these calculations that computers have achieved what they could achieve today. You can actually perform any conceivable calculation on your computer, it just depends on if you can speak the computers language.
Fortunately, that’s why we’re here.
Now delete everything except the original integer variable and the print statement. Then add this:
int secondNumber = 28;
int answer = firstNumber + secondNumber;
System.out.println(“The sum total is ” + answer);
Now what we’ve done is store two numbers into two separate variables and tell the system to add them together (+ is the operator for addition). The system then prints out the sum total with the message in quotes. If you run it, we should get this:
Image
If you don’t, either your codes wrong, or your computer just doesn’t know math. (That’s what you get when you by a computer from a guy in a street corner).
You can also add numbers directly into the variable. Add the figure 17 to your variable answer, so that it looks like this.
int answer = firstNumber + secondNumber + 17;
Run it and you should get 65. If you don’t, make sure you get you get your money back from street corner guy!
The other arithmetic operators include minus sign (-) for subtraction, asterisk (*) for multiplication, and backward slash (/) for division. Try them out in your code for fun. You don’t even have to confine yourself to only two variables. Make more and more, and even experiment with double and float.

Next week, we’ll continue on variables, and treat more variable types. We’ll also be sure to do more coding practice.
And speaking of practice, remember that you can only get better through it. It does make perfect.

Thanks for reading
Noeik