DEV Community

John Hill
John Hill

Posted on

Java Variables

In my last blog I explained that I even though I have been coding due to academic integrity I haven't been able to upload my code to Github. So to now get into the good stuff that I have been learning and working on. Summer B session has officially started back for me at ASU. The coding language I will be using this semester is Java. So while I am reviewing the basics and getting started I figured I go ahead and start with something simple as my first blog about code in a while. This will give you the basics of declaring and assigning variables in Java.

In java declaring variables all follow a basic format:

type name;

If you have never used Java than it is important to know that there are both primitive and object types. The primitive data types in Java are byte, short, char, int, long, float, and double. In Java the object types are Byte, Short, Character, Integer, Long, Float, Double, and String. If you notice all primitive data types start with a lower case letter and object types all start with a capital letter. So as I said know this declaring variables becomes pretty simple a few examples are:

int myInt;
double myDouble;
String myString;
Integer myInts;

Primitive vs. Object Data Types Basics

Primitive data types are predefined in Java. When a variable is created and another copy of the variable is created and changed the changes made in the copied variable will not reflect in the original variable. Where as Object data types are created by the user in Java. These Object Data Types could be class, array, string, ect. So when you create another variable and make it equal another Object Data Type they both reference the same object in memory so any changes made to either variable make changes to the object in memory and will be reflected in both.

Assigning Variables

In java you can assign a variable on the same line you declare it or you can assign it in a separate line after declaring the variable. The important thing to remember is that you if you try to assign a int to a char for instance if it is single digits it will assign it as a character and not the number if it is double digits for instance it would not work.

int z; 
z = 10; 
String myString = new String("Hello World");
char myChar;
myChar = 10,   <---- this would not work because char is a 
                     single character ---->

Top comments (0)