D1J1T Article Categories:

Programming   Management   Development   Design   HTML   JavaScript   CSS   PHP   MySQL   Database   Server   Audio   Object-oriented Programming   Hosting   Mobile   Social Networking   Java  

Java Programming Overview

Overview and Basics

by D1J1T — in Java — Updated: Feb 12, 2015 at 11:55 am

The goal of this article is to provide an introduction to the basics of programming in Java. It is written with no assumptions of prior programming experience and in a sense meant as a "crash course" to enable quick learning.

Let's Not Waste Time

Before we dive right in, let's ensure you're not wasting your time here. If your goal is to learn how to make a web page, you should learn HTML, CSS, JavaScript, (probably in that order) and for more advanced web programming, learn PHP|ASP|JSP and a database like MySQL or PostgreSQL.

If your goal is to write a complex network game application, full of 3d animations and sound for a specific platform like the XBox, I'd recommend learning C++ instead. (Also hiring a team and/or planning not to sleep any year soon.)

Want to be a mobile application developer? First read Mobile Application Types and decide if you want to code a native application or a web application. If this is the case, read on only if you want to program native Android apps. If you want to program native iOS apps, learn Objective C instead.

If you want to learn advanced programming concepts and skills that can be applied to other programming languages, using a language that is powerful, portable, and platform-independent, then read on. Java is currently the second most popular language, right below C. Note: C is low-level and very fast, better for system-specific applications. It is not object-oriented (though C++ is). As a first language, in order to best understand concepts, Java is ideal.

Still Here?

Great! Now, we have to get some boring setup/config stuff out of the way before we can get to the nuts & bolts of the language. You'll need to be able to both compile and run Java programs of course. To do so, you'll need to setup your working environment on your system. Grab the Java SE for free and follow the instructions on Oracle's site in order to install and configure it properly for your operating system. You may also want to consider downloading an IDE such as Eclipse to make your life a tad easier. Also, know that there are environments online where you can upload and test your code. If you're serious about learning and developing, install Java on your system.

Test Your Environment

Ok, so you think you have your system setup properly? Let's make sure. Copy and paste the following basic program into your editor and save the file as (ensuring proper case) "HelloWorld.java" without the quotes:
  public class HelloWorld {

    public static void main(String[] args) {
        System.out.println("Hello, World");
    }

  }
The next step is to compile using the tools in your IDE or if you are simply using notepad, you'll have to use the command line tool. Ensuring your path is set properly, you can browse to the file and type (without the quotes) "javac HelloWorld.java"
If your environment is setup properly, you'll notice a brief (one second) pause, and then should get no errors. If you do get errors, make sure the above code is copied and pasted exactly. Try to close/re-open to ensure no encoding issues, and ensure that you saved the file as HelloWorld.java If you've checked all of these, your environment is not setup properly. Now type (without the quotes) "java HelloWorld" (also without the .java). If all goes well, you'll see the string "Hello, World" printed out to the console and are now ready to start learning some code!

public Who? static What?

Don't worry, before you know it, these Java keywords will be commonplace. They are case-sensitive. Let's go through this simple application word by word. If you haven't already seen, this app, as most first programming language applications, just prints "Hello, World" to the console.
public is a Java access modifier. protected and private also exist in the language. For now, know that any other Java statement can "call" this method because it's public.
static is a bit complex to initially understand. It means that there will be only one shared copy of this (method or variable) for every instance of this class. Keep that in the back of your mind, but don't let it worry you for now; we'll come back to it. void just means that this particular method/function doesn't return a value. main is the name the we as the programmer give the method (all except for this one and a select few others). The () parenthesis contain the parameters of the function/method. When the method is called, arguments can be passed to the function. String is a class and args[] is a variable that we name that is of the type class String. The [] signify that it is also an array. Again, we'll come back to this. For now just try understand a bit of what was mentioned and that the only purpose of this application is to print one statement. System is a class, out a static variable, and println() a method.

That's a good bit to digest for one simple program that just prints a simple message!!! Don't worry if it all doesn't click right away. We'll be revisiting keywords often and going into more depth later. For now, if you saw the message being printed in your console, you're doing great! Go ahead and change the text in the quotes and re-compile. When you re-run, I'm sure you can predict the outcome! Next we'll start getting into some of the real meat of the language.

Java Variable Types

Unlike JavaScript for example, in Java, the type of a variable is vital. Let's consider the following two variable declarations, first in JavaScript:
  var myNum = 3;
  var myChar = 'c';
now in Java:
  int myNum = 3;
  char myChar = 'c';
Instead of using the JavaScript "var" keyword, in Java, we use the proper keyword based on the type the variable needs to be. There are 8 primitive types, and unlimited "class" or reference types. Let's discuss the primitives first. 6 of them are typically used for numbers, storing different sizes, with or without a decimal, signed or not. These are: byte, short, int, long, float, double. You can reference the specific sizes for these, but for now, know that unless you're calculating using very large (or very small) values, you'll be fine using an int for numbers (I believe it will store between (-2^31) and (2^31-1) (please email me any corrections) that don't need a decimal, and float for those that do. If you are working with MOL or light years, definitely research and ensure you're storing the right type, because your app will have errors if you attempt to store a large value where it won't fit.

I'll never forget a horror story of a programmer attempting to be efficient when writing software for an x-ray machine. Back then, programmers had to worry about every little byte and so he did. He neglected to take into account a certain case scenario however, and the machine ended up frying someone. When they studied the reason, they found the culprit to be just one variable, stored as a smaller type than the number needed. A life destroyed to save a register, to save space... So that's my disclaimer. I'm saying you will mostly use int and float, but ensure that's all that you need!

6 types are for numbers, only 2 of which you'll more than likely use most: int and float.
The other two primitive types are char and boolean. char is for characters: 'a', 'e', 'z', etc. boolean (named after Charles Bool I believe) is for true/false (also can be 1/0). Those are all of the primitive types. Now let's discuss the class or reference types.

Don't let this overwhelm you, but there are unlimited class type variables, and the number continues to grow. The reason is that the Java language was meant to be expanded, built upon, extended, and it has!

If you look back at our first app, you'll notice the variable "String args[]". The reason the "S" in "String" is in uppercase is because it's a class variable. All class variables (also class names) start with an uppercase letter. Primitive variable types use the specific Java keyword instead and are in lower case.

Let's recap variables. There are 8 primitive types and unlimited class types. The primitive types (remember int, char, boolean, float at least) are lower case, whereas the class types are upper case. Variables define the state of an object. More on that later.

Variable Declaration and Initialization

Below we'll declare and also initialize some variables. Know that // is a line comment (the compiler ignores the rest of the line)
  int myNum; //declared, but not initialized. if this variable is accessed in the program, a null pointer exception will be thrown
  int alsoMyNum = 3; //declared and initialized as all of the others below.
  int yetAnotherNum = 7;
  float numWithPoint = 0.3;
  char myLetter = 'd';
  boolean mySwitch = true;
  DJSCustomClass djscc = new DJSCustomClass("strArg1",7,false);
We'll discuss operators more in depth later. For now, know that in each above, the right side of the "=" is assigned in the variable name on the left. So if I declare int mySum = alsoMyNum + yetAnotherNum; (note the semi-colon to end all Java statements) then the variable mySum will store the value 10 and when referenced will not be null. Note that null does not equal 0, rather means non-existent. Note the last declaration as well. This reference is the only non-primitive or class/reference type. Some of these are already a standard part of the language (String, Integer, Color, Paint, Bundle, Math, Applet) are common examples. There are many, many others. These classes are put into packages that you can import into your programs, allowing you to use the pre-written classes, methods and variables. Thinking that someone may have already written the same function that you're working on? You're probably correct. Reference the docs often! This is a great feature of the language. You and I can write and share our own packages of classes! For now, just note that the declaration begins with the class name (starting in uppercase) then a name that I choose (in this case "djscc", admittedly not the best variable name), and we then assign this variable to a new instance of the class. Know that "new" is a Java keyword and signifies creating a new object of that class type. (There are also arrays, which are also common, and we will address later.) This is probably the greatest part of the language. It doesn't matter what you're working on, you can make an object template for it, or a Java "class". Then you can use that template, create thousands of these objects easily (in one line of code) and then alter only the certain specifics needed for each. Here's a real world example.

I Like Cats!

Any of my family will tell you this is true and how annoying it is to them. So I'm going to use animals, cats in particular as an example, but know that we could be using cars, coins, clothes, colognes, colors, chemicals, cellos, coffees or chickens instead. We could be using any object, those that don't begin with the letter 'c' included of course. :) So just imagine your favorite object and attempt to apply to the following.

  public class Animal {
  
  }
This is my simple class definition. Note the { } that will contain all of the code for this class. This class is very general. It doesn't define all of the characteristics of a cat, nor its behaviors (or Animals yet even). However, there are some things that are common to almost all animals. Let's define some of these. That way, when we extend or subclass this "Animal" class with a class that we name "Cat", we won't have to create new variables for "number of legs" for example. We just override those specific variables/methods when needed. This isn't a big deal when you're only dealing with a couple of cats, but what if you're studying the survival rate of white tigers or running a no kill shelter for cats and dogs? This template may be useful:
  public class Animal {
    int numLegs;
	boolean isHungry;
    String soundMade;
	public void makeNoise() {
	  playSound(soundMade);
	}
  }
Given this, we can now create a "Cat" class to better define our cats, without affecting any dogs or other animals:
  public class Cat extends Animal {
    
  }
This class already contains the space allocated for the variables (numLegs, isHungry, and soundMade) and also the method (makeNoise();) Now let's better define our "Cat" class, using our inherited variables, while also creating some more:
  public class Cat extends Animal {
    public Cat() {
	  numLegs=4;
	  isHungry=true;
	  soundMade="Meow";
	  makeNoise(soundMade);
	}
  }
The first important thing to notice here is the line before the class declaration. The "public Cat()" is called a constructor and as the name implies, constructs the object. This is the method that is called when the Java keyword "new" is used. This particular constructor doesn't contain any parameters, however, I could have included any that I wanted. For example, we could pass the value "true" or "false" as an argument in the constructor and assign it to the "isHungry" variable. So you can imagine, we could make 100 cats and make 20 of them hungry initially. This can be done with any variable of course, so we could have cats with 17 legs if we wanted, make some "bark", some "quack", etc. The point is that we don't have to re-write code for every object. We use a template and adjust where we need to to better define each individual object only as needed and use our super class template for the rest where the default values apply.
This is the power of inheritence. As you can imagine, We can extend the "Cat" class by making a subclass "MaineCoon". This may contain its own variables that further define this breed: bodySize="large" for example. The main point to comprehend is that a "MaineCoon" is of type "MaineCoon", but it is also a type "Cat" and also an "Animal". We could further define our objects by adding a "Feline" class maybe. This applies to any and all objects. Templates are created and used to save time.

Since we're discussing inheritance, we should also touch on encapsulation and polymorphism. Don't let these terms scare you. We've already discussed polymorphism which basically just states that a "Cat" is a "Cat", but it is also an "Animal". This means that we can reference a "Cat" as a cat when needed, but sometimes its better to reference as an animal, and we have the choice.

Encapsulation is just the concept of the separation of code. When you call a method to make cat1 purr, you don't have to worry about all of your other cat's purring also. Their code is encapsulated. With this, and inheritance, you're given the power to expand easily, but also edit individually. See OOP for more details on object-oriented programming for more specifics.

And Now, More Syntax

It's horrible, I know. It's not fun. I can't tell you how many times I've forgotten a semi-colon, typed a class, method, or variable in the wrong case, or forgot a "}". That's not the worst of it even... You'll get errors like "This class should be in it's own file." or "static variable myCoolX should be accessed in a static manner" and many others. Why do I know them? Yes, because I've seen them several times. They will annoy you as they did me. At the same time, you'll learn more of the specifics of the language, so my best advise is to read them, fix them, and move on. Who was it that said, "Experience is the best teacher?" I'd guess many would agree... I can merely give you some hints like, "don't forget your ; when ending your statements." and "Check your close ", ), }, ], etc." Also, know that Java typically uses "camel-case." Look it up and learn it! Also, learn all of the keywords. And test, test, test. Print your variables out to the console to ensure they contain the value that you think they should at the time. Now, read that sentence again if you're a new programmer, because it applies to all languages and is a simple, yet useful, debugging skill. I have wasted time editing code that wasn't malfunctioning, only to find out later that another section of my code had a silly error. (Dang! I forgot to cast that to an int type! or Wow, I didn't alter that variable in the function I'm calling even though I thought I was!!!) You will as well... (Not me!?!!) Yes, you as well. It's easier to do than you'd imagine, trust me. My best hint (also probably the best sentence in this article): print out your variables and re-compile often. If you think dealing with syntax errors are bad, wait until you experience semantic or logic errors and have to do some real debugging.

Know that there are other syntax-specific issues that I'm choosing not to bore you with. If you're getting errors, and even if not, it'd be good for you to learn all of the syntax specifics in order to save you some time and overall headaches. (classes start with the first letter being uppercase, all others lowercase, and the start of each other word in the variable capitalized as well. Variables and methods (functions) start in lowercase, but then follow the same pattern. Know the difference. If you can't point out a class from a variable from a method, backup and learn how to do so properly.

So Now I Know Where to Put My ; !!!

You know the proper syntax of the Java language, as well as its power, but need some more info. Of course you do. Again, know that despite you'll be creating your own specific code, you'll be importing others and re-using their's more often:

import java.awt.*;
import java.applet.Applet;
import java.coolPackage.CoolerClass;

  public class Cat extends Animal {
   ...
  }
java.util is imported by default if I'm not mistaken. Other's you'll have to specifically import as in the above example. The third line won't work. It's simply an example of the power of extention and inheritence. If I did make a "CoolerClass" and put it in a "coolPackage" AND it was accepted by the Java language, it would work. Even if not accepted, if used by only me, and my paths are setup properly to where my app can find that package, then I could use it.

There is much that I have not covered in this tutorial. Know that I first learned Java in 1995. I've used it for many applications since then. I realize how this article doesn't give certain specifics. There are a lot. There are other concepts not covered as well. Know that I'll be happy to answer any questions though, if you are seriously interested, seriously need help with a project, or are just curious. I've attempted to give an overview and a crash-course in the same article. I'll be happy to answer what I can (that I haven't here). Just email me. Thanks for reading!

A day after writing this, I felt a tad guilty... like I didn't give those new to programming or to Java enough to work with initially. So, I've decided to add this list of tips as well below. I may be repeating a couple; know they are important!
  • This one you should know already. If you don't know something specific, Google it. Getting a unique error? I'd bet it's not very unique. More than likely, someone else has had that problem. You'll find Stack Overflow. to be an excellent source. It's answered hundreds of my questions.
  • Take online tutorials. A lot of them. They're free!!!
  • Again, reference the Java docs often.
  • Learn camel-case. It's simple. I should've explained it already, but here it is. class names start with an upper case letter. Everything else starts with a lower case letter. With variables and methods, they start with lower case, then every word contained within is capitalized. For example: myFirstVariable OR myFirstMethod();
  • Print out your variables to your log or console at least. If you don't know the value of one, make sure you can see it. This applies to colors as well for example. If you need to see the color of a square, write helper code to do so.
  • Re-compile often and test, test, test... Every case you can think of. Your users will think of others.
  • Plan you're project out well. This will save you time. I promise. It is painful to spend days on a project only to realize that you should've used other structures.
  • Variables are for the program/object state and there are 8 primitive types and unlimited class types.
  • Methods define the program or object's behavior.
  • Classes are a template for an object.
  • Packages are libraries of classes that are related.
  • In the example above, the makeNoise method is defined in the Animal class, but is called (executed) in the Cat class.
  • Java uses common operators: +, -, *, / for math. Also % (modulus) will return the remainder. ++ will increment, -- will decrement.
  • Logical operators include && (AND), || (OR), ! (NOT)
  • Don't confuse = (assignment) with == (comparison)
  • Conditionals/comparisons are used in if, if...else, while, do...while, for, switch
I realize that I haven't covered enough still. Look for a part two soon or feel free to contact me with any questions.


If you find these articles to be helpful, I could always use another cup of coffee! Social media likes/+1s are also much appreciated. Thanks for reading!

Add Comment to Post: