0% found this document useful (0 votes)
114 views

Java With Khatea

The document provides an introduction to Java programming concepts like classes, objects, methods, and loops. It explains that in Java, everything needs to be inside a class. A class acts as a blueprint that defines the structure and behavior of objects. The document also covers primitive data types in Java, conditional statements using if/else, arrays, and the for and while loop structures. It includes code examples and explanations for a basic "Hello World" program, defining classes and objects, using primitive types and strings, if/else statements, iterating over arrays using for loops, and while loops.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
114 views

Java With Khatea

The document provides an introduction to Java programming concepts like classes, objects, methods, and loops. It explains that in Java, everything needs to be inside a class. A class acts as a blueprint that defines the structure and behavior of objects. The document also covers primitive data types in Java, conditional statements using if/else, arrays, and the for and while loop structures. It includes code examples and explanations for a basic "Hello World" program, defining classes and objects, using primitive types and strings, if/else statements, iterating over arrays using for loops, and while loops.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 55

LET’S LEARN SOME

JAVA
HELLO WORLD

Java is an object oriented language (OOP). Java objects are part of so-called "Java classes".

Let's go over the Hello world program, which simply prints "Hello, World!" to the screen.
WHAT IS A CLASS? public class Main {

In Java, every line of code that can actually run needs to be inside a class. This line declares a class named
Main, which is public, that means that any other class can access it.

In Java, a class is a blueprint or a template that defines the structure and behavior of objects. Objects are
instances of classes. A class can contain fields (variables) to store data and methods (functions) to perform
actions. It's like a blueprint that defines what an object of that class will look like and what it can do.

Here's a simple example of a class in Java:


EXAMPLE EXPLANATION

In this example, the Car class has three fields (make, model, and year), a constructor (a special method used to
create objects), and a method (startEngine) that can be called on objects of the Car class.
Now, let's talk about public and private:

Public: When a field or method is declared as public, it can be accessed from anywhere, including other classes. For
example, you can create an instance of the Car class and call its startEngine method from any part of your code.
Private: When a field or method is declared as private, it can only be accessed within the same class. Other classes
cannot directly access private members. This is used to encapsulate the internal workings of a class, ensuring that
the implementation details are hidden and preventing unintended interference from other parts of the code.

For example, in the Car class above, the fields make, model, and year could be declared as private to ensure that only the
methods within the Car class can access and modify them. You can provide public methods (often called getters and
setters) within the class to allow controlled access to these private fields from outside the class.
Here's a simplified example of using private fields and public methods:
HELLO WORLD

Java is an object oriented language (OOP). Java objects are part of so-called "Java classes".

Let's go over the Hello world program, which simply prints "Hello, World!" to the screen.
NEXT LINE IS -

This is the entry point of our Java program. the main method has to have this exact signature in order to be
able to run our program.

● public again means that anyone can access it.


● static means that you can run this method without creating an instance of Main.
● void means that this method doesn't return any value.
● main is the name of the method.

The arguments we get inside the method are the arguments that we will get when running the program with
parameters. It's an array of strings. We will use it in our next lesson, so don't worry if you don't understand it
all now.
● System is a pre-defined class that Java provides us and it holds some useful methods and variables.
● out is a static variable within System that represents the output of your program (stdout).
● println is a method of out that can be used to print a line.
LESSON 2!

Although Java is object oriented, not all types are objects. It is built on top of basic variable types called primitives.

Here is a list of all primitives in Java:

● byte (number, 1 byte)


● short (number, 2 bytes)
● int (number, 4 bytes)
● long (number, 8 bytes)
● float (float number, 4 bytes)
● double (float number, 8 bytes)
● char (a character, 2 bytes)
● boolean (true or false, 1 byte)

Java is a strong typed language, which means variables need to be defined before we use them.
NUMBERS

To declare and assign a number use the following syntax:

Or
To define a double floating point number, use the following syntax:

If you want to use float, you will have to cast:


Characters With String

In Java, a character is it's own type and it's not simply a number, so it's not common to put an ascii value in
it, there is a special syntax for chars:

String is not a primitive. It's a real type, but Java has special treatment for String.
Here are some ways to use String:
There is no operator overloading in Java but there is the exception that proves the rule - string is the only
class where operator overloading is supported. We can concat two strings using + operator. The operator +
is only defined for strings, you will never see it with other objects, only primitives.

You can also concat string to primitives:


BOOLEAN

Every comparison operator in java will return the type boolean. Unlike other languages, it only accepts two
special values: true or false.
CHALLENGE

Create all of the primitives (except long and double) with different values. Concatenate them into a string
and print it to the screen so it will print: H3110 w0r1d 2.0 true
LESSON 3: CONDITIONALS (wohoo)

Java uses boolean variables to evaluate conditions. The boolean values true and false are returned when
an expression is compared or evaluated. For example:
Of course we don't normally assign a conditional expression to a boolean. Normally, we just use the short
version:
Boolean Operators

There aren't that many operators to use in conditional statements and most of them are pretty straight
forward:
IF ELSE AND BETWEEN

The if, else statement in Java is pretty simple.

And we can also add an else statement after an if, to do something if the condition is not true
The if - else statements doesn't have to be in several lines with {}, if can be used in one line, or without the {},
for a single line statement.

Although this method might be useful for making your code shorter by using fewer lines, we strongly
recommend for beginners not to use this short version of statements and to always use the full version with
{}. This goes to every statement that can be shorted to a single line (for, while, etc).
THE UGLY SIDE OF - IF :(

There is a another way to write a one line if - else statement by using the operator ? :
== and equals

The operator == works a bit different on objects than on primitives. When we are using objects and want to
check if they are equal, the operator == will say if they are the same, if you want to check if they are logically
equal, you should use the equals method on the object. For example:

String a = new String("Wow");


EXERCISE

Change the variables in the first section, so that each if statement resolves as true.
ANSWER
EXPLANATION:

Changed String a = new String("Wow"); to String a = "Wow";. Using string literals creates the string in the string pool, which ensures
that both a and b reference the same string object.

Changed String b = "Wow"; to String b = "Wow";. This is also a string literal.

String c = a; and String d = c; remain the same.

With these changes, each if statement will resolve as true, and the output will be: SUCCESS NICEEEEEEEEEEEEEE
LESSON 3: OMG,,, ARRAY NA!

CONGRATS ON GETTING THIS FAR, DO YOU KNOW THAT ARRAYS ARE ONE OF THE HARDEST BUT USEFUL
PARTS OF PROGRAMMING!? KERI ITEY
Arrays in Java are also objects. They need to be declared and then created. In order to declare a variable that
will hold an array of integers, we use the following syntax:

Notice there is no size, since we didn't create the array yet.

This will create a new array with the size of 10. We can check the size by printing the array's length:
We can access the array and set values:

Java arrays are 0 based, which means the first element in an array is accessed at index 0 (e.g: arr[0], which
accesses the first element). Also, as an example, an array of size 5 will only go up to index 4 due to it being 0
based.
We can also create an array with values in the same line:

Don't try to print the array without a loop, it will print something nasty like [I@f7e6a96. To print out an array,
use the following code:
CHALLENGE!

Change the values in numbers so it will not raise an error.


ANSWER
EXPLANATION

Changed int length = numbers[3]; to int length = numbers.length;. This gets the length of the numbers array rather
than accessing an invalid index.

Changed char[] chars = new char[length]; to char[] chars = new char[length];. Using the correct length variable
ensures the array is created with the appropriate size.

Changed chars[numbers.length + 4] = 'y'; to chars[numbers.length - 1] = 'y';. Since array indices start from 0, you need
to subtract 1 from the length to access the last element of the chars array.
LESSON 4: LOOPS <3
There are two kind of loops in Java, for and while.

FOR:
The for loop has three sections:

First section runs once when we enter the loop.

Second section is the gatekeeper, if it returns true, we run the statements in the loop, if it returns false, we exit
the loop. It runs right after the first section for the first time, then every time the loop is finished and the third
section is run.

The third section is the final statement that will run every time the loop runs.

So in the case we have just seen, the loop will run 3 times. Here is the order of the commands:
We can omit the first and third section of the loop (although it will be weird), and the loop will still work:

For cases where we want to use a loop that look like that, we use a while loop
WHILE LOOP

The syntax is very similar to the previous for we looked at:

The condition will run for the first time when entering and every time the loop is done. If it returns false, the
loop will not run. If we want the loop to always run at least one, we can use do-while

Notice the ; in the end of the do-while.


For Each

Another version of for, is the foreach. The keyword we use is still for, but when we want to iterate on the
elements inside an array we can simply use it:

Notice that if you want to use the index of the element inside the loop, you have to use the longer version
and can't use foreach.
Break and Continue

These two keywords help us control the loop from within it. break will cause the loop to stop and will go
immediately to the next statement after the loop:
continue will stop the current iteration and will move to the next one. Notice that inside a for loop, it will still
run the third section.
EXERCISE

Loop through and print out all even numbers, each in a separate line, from the numbers list in the same order
they are received. Don't print any numbers that come after 237 in the sequence.
public class Main {

public static void main(String[] args) {

int[] numbers = {

951, 402, 984, 651, 360, 69, 408, 319, 601, 485, 980, 507, 725, 547, 544,

615, 83, 165, 141, 501, 263, 617, 865, 575, 219, 390, 984, 592, 236, 105, 942, 941,

386, 462, 47, 418, 907, 344, 236, 375, 823, 566, 597, 978, 328, 615, 953, 345,

399, 162, 758, 219, 918, 237, 412, 566, 826, 248, 866, 950, 626, 949, 687, 217,

815, 67, 104, 58, 512, 24, 892, 894, 767, 553, 81, 379, 843, 831, 445, 742, 717,

958, 609, 842, 451, 688, 753, 854, 685, 93, 857, 440, 380, 126, 721, 328, 753, 470,

743, 527};

// Your code goes here

}
LESSON 5: Functions : >

In Java, all function definitions must be inside classes. We also call functions methods. Let's look at an
example method

foo is a method we defined in class Main. Notice a few things about foo.

● static means this method belongs to the class Main and not to a specific instance of Main. Which
means we can call the method from a different class like that Main.foo().
● void means this method doesn't return a value. Methods can return a single value in Java and it has
to be defined in the method declaration. However, you can use return by itself to exit the method.
● This method doesn't get any arguments, but of course Java methods can get arguments as we'll see
further on.
Arguments
I always like to say that arguments to Java methods are passed by value, although some might disagree
with my choice of words, I find it the best way to explain and understand how it works exactly.

By value means that arguments are copied when the method runs. Let's look at an example.

Here is a another place in the code, where bar is called

You can picture in your head that when bar(a, b) is run, it's like in the beginning of bar the following two
lines are written:
And only then the rest of the method is run.

This means that a value get copied to num1 and b value get copied to num2. Changing the values of num1 and
num2 will not affect a and b.

If the arguments were objects, the rules remain the same, but it acts a bit differently. Here is a an example:

And here is how we use it

Again we can picture the same two lines in the beginning of bar2
But when we assign objects, it's a bit different than assigning primitives. s1 and joe are two different
references to the same object. s1 == joe is true. This means that running methods on s1 will change the
object joe. But if we'll change the value of s1 as a reference, it will not affect the reference joe.
Non Static Methods
Non static methods in Java are used more than static methods. Those methods can only be run on objects
and not on the whole class. Non static methods can access and alter the field of the object.

Calling the methods will require an object of type Student.


EXERCISE!

Write the method printFullName of student which prints the full name of a student.
SOLUTION
Lesson 6: Objects

Everything in Java is within classes and objects. Java objects hold a state, state are variables which are
saved together within an object, we call them fields or member variables.

This class defined a point with x and y values.

In order to create an instance of this class, we need to use the keyword new.

You might also like