Jump to content

[Tutorial]Basic Java| Variables | Loops | Conditionals | Methods | Classes


Nicolás™

Recommended Posts

What Is Java?

 

Java is a programming language originally developed by James Gosling. The language derives much of its syntax from C and C++ but has a simpler object model and fewer low-level facilities. Java applications are typically compiled to bytecode (class file) that can run on any Java Virtual Machine (JVM) regardless of computer architecture. Java is a general-purpose, concurrent, class-based, object-oriented language that is specifically designed to have as few implementation dependencies as possible.

Read more here.

 

Hello World (code)


public class HelloWorld{

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

Hello World Explained

 

Let's look at the code line by line.


  •  
  • public class HelloWorld{
     

    •  
  • This line defines the class name. The syntax of defining classes is: AccessType class ClassName { Notice the line ends with an opening bracket. Every time you define a class, you have to use opening and closing brackets.
     
  • When saving a Java file, the name of the file must be the ClassName. So the HelloWorld class above must be saves as HelloWorld.java
     
     

 

[*] public static void main(String[] args) {

 


  •  
  • This line is the header of the main method. Every main method has a header like this. Methods will be covered in detail later on.
     
     

 

[*] System.out.println("Hello World!");

 


  •  
  • This line is what says what's going to happen. System.out has many different type of print mehtods. I'll discuss two of them here.
         

    •      
  • The System.out.println method prints the parameter (what's in the parenthesis) on a new line in the console. This method can also be used without any parameter and that will make the console print an empty line. System.out.println() is useful to print new lines in the console.
         
  • The System.out.print method is similar to the println method, but this doesn't print a new line. This method will print something on an existing line in the console. Because of this, if you don't put anything in the parameter, unlike the println method, you'll get a Syntax error (an error which won't let you compile the code).
         

      [*] You can change what gets printed by changing the parameter. If you'd like to print Hey, Saad you'd use: System.out.println("Hey, Saad"); If you are printing a number, you don't need the quotation marks. However if you want to print a string (set of characters) you must use parenthesis.

      [*] Most statements in Java need to end in a semicolon except methods, conditionals, and class declarations.

 

 

 

[*] }

  • Remember this rule: Every bracket which is opened must be closed.
    The first parenthesis is closing the main method. The second parenthesis is closing the class. Not including any of these parentheses will result in a Parsing Syntax Error.
     

I'll be covering classes and methods in more detail later on.

 

 

Defining Variables

 

A variable is an object that can hold a specific type of data. So you can basically assign a value a name and get the value by using the name instead of the value. There are many types of variables and you can also create your own types of variables. (Will be discussed later on). Here are the most common variable types:

  • int - An int is an integer which can hold whole numbers under 2.17 billion in size.
  • long - A long is just like an integer but it can hold whole numbers larger then 2.17 million.
  • double - A double can contain numbers with decimal values.
  • boolean A boolean holds only two values, true or false (0 or 1).
  • String - A string holds more than one character which can include numbers, symbols and characters. When assigned a value it needs to be assigned with quotation marks before and after the value ("").
  • char - A char holds only one character. When assigned a value it needs to be assigned with a apostrophe before and after the value(').

Defining variables is easy. There are two ways you can instantiate a variable. The first way is to declare it and assign it at the same time. For example:


int num = 1;

Here we are making an int with the name num and it contains the value 1. The default way to make these types of variables is:


type name = value;

Here the type is the object type (int, double, String etc). The name is any name you want. However, you can define two variables with the same name. The value is the data that is assigned to the name.

Now what if you want to declare a variable but use it later?

Well you can define a variable and set it later. For example:


int num;
//other code (this is a one line comment, this will not be read by the compiler).
num = 1;

Here you are declaring the variable, but setting it later. If you try to use the variable without assigning it a value, you'll get a syntax error.

 

You can also assign one variable the value of another. For example:


int a = 1;
int b = a;

Here b will also be equal to 1.

 

Basic Scope

 

Variables made in the main method will only be able to be used there. If you decide to make a different method and use variables in the main method in the other method, you'll get a syntax error. (Methods will be discussed later on). To fix this, you can define global variables. Global variables can be accessed any where in the class. When declaring global variables you can set the access level. The access level is how your variable can be accessed, meaning can other classes see it or not (classes will be covered later on).

The two common access levels are:

  • public: The access level public means that other classes can see it.
  • private: Other classes cannot see a variable with access type of private.

This is where you would declare global variables:


public class HelloWorld{

public int a = 1;
public int b;

public static void main(String[] args) {

}
}

 

Using Variables

 

There are many uses for variables. You can use them to add. For example:


int a = 1;
int b = 2;
int c = a + b;

Here c  will be equal to 3 because 1 + 2 = 3.

 

Here are some operators which can be used with ints, floats, doubles, and longs in Java:

  • +: This is the addition operator.
  • -: This is the subtraction operator.
  • /: This is the division operator.
  • *: This is the multiplication operator.
  • %: This is the modulus operator. This will give you the remainder of two numbers. E.g 5 % 2 = 1 because when dividing 5 by 2 you have a remainder of 1.
  • ++: This is the increment operator. This will increase the value by 1. E.g If we have a variable x with the value 2, after x++ the value will be 3.
  • --: This is the decrement operator. This will decrease the value by 1. E.g If we have a variable x with the value 2, after x++ the value will be 1.

 

Another important thing you can do with variables is print them.


String abc = "Hey";
int num = 3;
System.out.println(abc);
System.out.println(num);

This will print:


Hey
3

 

Conditional Statements

 

Conditional statements basically say that if a condition is met, only then will a piece of code get executed. There are three types of conditional statements.

  • The if statement
    • This basically means that if a condition is true then the code will get executed. If the condition isn't true, nothing will happen. For example:


int num = 1;
if(num == 1){
System.out.println("Num = 1");
}

Here if num is assigned to be 1, there will be a print statement saying num is 1. If not nothing will happen. Now notice how the if statement is worded:


if(VariableNameOrValue == AnotherVariableNameOrValue) {
//code to be executed if the statement is true.
}

Notice the two equal signs. You have to have the two equal signs or you'll get an error.

[*] The if else statement

  • This lets you execute one piece of code if something is true and another if it isn't. For example (I'll use booleans since I have shown you how to define them):

    boolean a = false;
    if(a == false){
    System.out.println("A is false");
    } else{
    System.out.println("A isn't false.");
    }
    //you can also use this with numbers. For example:
    int b = 2;
    if(b == 2){
    System.out.println("B is 2");
    } else{
    System.out.println("B isn't 2");
    }
    
    


[*] The if elseif Statement

  • The if elseif Statement goes through two or more statements one by one and if any of them is true, it executes the code in the statement and stops. For example:

    int b = 2;
    if(b == 1){
    System.out.println("B is 1");
    } else if(b == 2) {
    System.out.println("B is 2");
    }else if(b == 3) {
    System.out.println("B is 3");
    }else {
    System.out.println("B isn't 1, 2 or 3");
    }
    
    


      • Notice how you can use else statements with an else if statement.

Other operators

Now what if you don't want to see if something is equal. What if you want to check is something is bigger then something else? Well there are more operators you can use to compare two values.

  • >: This is the greater than operator. This will be true if the left value is greater than the right.
  • <: This is the less than operator. This will be true if the left value is smaller than the right.
  • <=: This is the less than or equal to operator. This will be true if the left value is smaller than or equal to the right.
  • >=: This is the more than or equal to operator. This will be true if the left value is bigger than or equal then the right.
  • !: This is the not operator. This will be true if the value isn't something.
  • .equals(""): This is the equals operator for strings. YOU CAN'T DO == WITH STRINGS. You have to use .equals().

Here's how you use some of these operators:


int b = 2;
if(b > 1){  //true
if(b < 1){  //false
if(b >= 1){  //true
if(b <= 1){  //false
if(b != 1){  //true
String a = "Saad";
String b = "a";
if(a.equals(b)){//if a equals b  -- False
if(!a.equals(b)){//if a does not equal b -- True

 

Loop Statements

 

A loop is a statement which allows code to be repeatedly executed. There are three types of loops. I'll be covering two types and the third type later on.

  • The While Loop
    • The while loop goes on till the condition inside it becomes false. Typically we use a counter or a boolean to control loops. Here is an example:


int counter = 0;
while(counter <= 10){
System.out.println(counter);
counter++;
}

//Heres a loop controlled by a boolean

boolean b = false;
int a = 0;
while(b == false){
System.out.println(a);
if(a == 10){
b = true;
}
}

These two loops are exactly the same thing and they both will print the numbers 0 to 10, each on a new line. Here's how most loops are formatted:


int counter = 0;
while(conditional which usually involves counter){
//code
//change counter so we don't result in an infinite loop.
}

An infinite loop goes on forever and will eventually slow down your computer.

[*] The For Loop

  • The for loop is just like a while loop but here you make the counter, add the condition and change it in one line. It's basically a way to write a while loop horizontally instead of vertically. Here's the basic syntax:

    for( create counter; condition; change counter ){
    //do code
    }
    
    


    Here's how you'd print numbers from 0 to on using a for loop instead of a while:


    for(int counter = 0; counter <= 10; counter++ ){
    System.out.println(counter);
    }
    
    


Some tips:

- Anything variable declared in the loop will only be accessible inside the loop. It will also be reset after the loop increments. The way to avoid this is to not declare variables inside the loop but declare it before the loop.

 

Methods

 

Suppose you want to do the same logic of code many times but with different values. Let's say you want to add two different values but the values will be different most of the time (like in a calculator). To do this you use methods. Methods have to be placed outside the main method but inside the class: For example:


public class HelloWorld{

public static void main(String[] args) {
System.out.println("Hello World!");
}
//method 1
//method 2
}

Methods can be classified into two types.

  • void: This type of method does not return any value. It only changes existing values. Here's how void methods look like:


AccessLevel void name(Parameters){
//code
}

Here's a completed method which displays numbers from 0 to 10 and how you can call the mehtod.


public class HelloWorld{

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

public void displayNumbers(){
for(int counter = 0; counter <= 10; counter++ ){
System.out.println(counter);
}
}
}

This code will display numbers from 0 to 10. Notice this method has no parameter. A parameter is a way of giving our method values to use.

Let's say you wanted a method to print numbers from 0 till x, where x can be any number. Here's how the method would look like:


public class HelloWorld{

public static void main(String[] args) {
displayNumbers(12);
}

public void displayNumbers(int x){
for(int counter = 0; counter <= x; counter++ ){
System.out.println(counter);
}
}
}

Notice three things here.

  • I now have something inside the parenthesis when calling the method. I have to have a number inside the parenthesis because the method has an int parameter. If I try to do displayNumbers("String"); I'll get a syntax error. I have to have an int inside the parenthesis.
  • The second thing is that I have included a parameter when defining a method. To add a parameter you have to add Type name in the parenthesis. To add multiple parameters you separate them with commas.
  • The third thing which I changed is the 10 in the counter. The 10 is now x meaning the loop will go on till counter is equal to x.

Here's a method which displays numbers from a to b. Where a and b are parameters and can be anything.


public class HelloWorld{

public static void main(String[] args) {
displayNumbers(1, 12);
}

public void displayNumbers(int a, int b){
for(int counter = a; counter <= b; counter++ ){
System.out.println(counter);
}
}
}

The return statement

The return statement can be used in void methods to stop a method early. It's optional but it can come in handy. For example let's say you want a parameter to be more then 0. So to implement this you can add a if statemenet and if it's true you can add a return statement. Here's an example of how you'd check to see if the parameter a is less than 0 and if it is how to stop it.


public class HelloWorld{

public static void main(String[] args) {
displayNumbers(1, 12);
}

public void displayNumbers(int a, int b){
if(a < 0){
return;
}
for(int counter = a; counter <= b; counter++ ){
System.out.println(counter);
}
}
}

[*] Methods that return something

You can also use methods to get values. Here's the basic syntax of defining return methods:


AccessLevel returnType name(Parameters){
returnType a = ...;
return a;
}

The return type can be any variable type. It can be a String, int, double or any type of variable. Notice how I have a variable (it can also be a value) after the return statement.

The return statement basically stops the method and sends a value/object back to the caller. (You'll understand later on with examples).

You have to have a return statement in a method that isn't a void method.

 

For example if you wanted to get what a + b is you'd make a method like this:


public int add(int a, int b){
int c = a + b;
return c;
}

See how I'm returning c? You can assign returned values to a variable of the same type. For example:


public class HelloWorld{

public static void main(String[] args) {
int c = add(1, 12);//here c will be 13
}

public int add(int a, int b){
int c = a + b;
return c;
}
}


This is just a beginner's guide to methods. Methods can get more complex and there are many types of methods (recursive, overloaded, overridden etc) which I may cover in a later tutorial.


Classes

 

Classes in Java is the last thing I'll be covering today. Classes are basically object types in Java. Remember how I said you can make your own variable types? Well this is how. You can have many classes in your program, but usually only one has a main method.

Classes are made to keep similar methods in one place or to make a new object type.

Classes are made like this:


accessType class NameOfClass{

}

Classes are made to keep similar methods in one place or to make a new object type.

  • Here's a class which has similiar methods together.


public class MathOps{
public static int add(int num1, int num2){
int answer = num1 + num2;
return answer;
}
public static int subtract(int num1, int num2){
int answer = num1 - num2;
return answer;
}
}

Here you see a new word: static. static methods can be used from other classes without making an instance of the class.  (You'll understand better when I show you the other type of class).

To use these methods from another class you'd do: MathOps.add(1, 2);

For example:


public class HelloWorld{

public static void main(String[] args) {
int c = MathOps.add(1, 12);//here c will be 13
}
}

[*] Classes which can be instantiated.

Here's an example of a class which can be instantiated:


public class Car{
private String make;
private String model;

public Car(String m, String m2){
make = m;
model = m2;
}
public void Drive(){
//drive code
}

}

Here you'll notice something that should ring bells in your brain. I HAVE A METHOD WITH NO RETURN TYPE? WHAT???

Well, notice how it has the same name as the class name. This is a constructor. A constructor is like a method but it doesn't have a return type.

It allows you make an instance of the object. You can have as many constructors as you want (they have to have different parameters) and ususally the parameters are assigned to the global variables (which are usually private).

To create instances of objects you use the following syntax:


ObjectType name = new ObjectType(Parameters if any);

 

Here's how you'd make a new Car object in another class.


public class HelloWorld{

public static void main(String[] args) {
Car a = new Car("BMW", "X5");
}
}

Basically that's making a new car.

I can make as many cars as I want:


public class HelloWorld{

public static void main(String[] args) {
Car a = new Car("BMW", "X5");
Car a = new Car("Mercedes", "S550");
Car a = new Car("Lexus", "RX400");
}
}

Back to the car class. Notice I have a drive method there. The drive method isn't static. That means I can't do Car.drive();

I can however do this:


public class HelloWorld{

public static void main(String[] args) {
Car a = new Car("BMW", "X5");
a.drive();
}
}


  • If I had a static method in the Car class, doing a.staticMethod would give me an error. I'd have to do Car.staticMethod

 

Well that's the end of the tutorial.

Have a good start on Java, Nicolás™

 

Link to comment
Share on other sites

axax Sex +1

 

Off:

[9:38:23 μμ] Nicolas™: pineis tpt re mlka? xD

[9:38:47 μμ] kOzA barney: Ligw xorto opos panda

[9:38:54 μμ] Nicolas™: x0ax0a

[9:38:54 μμ] Nicolas™: xD

Nicolas™

Link to comment
Share on other sites

  • 2 weeks later...

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.



×
×
  • Create New...