Java tutorial
Java is a cross platform compiled language that uses jvm (java virtual machine) that can be used in any machine no matter the hardware or software, provided the machine supports jvm
FYI
- The object class is the root of all classes
- Data can be gatered with the scanner method in the java library but cannot cater charecter type data with the standard library. Those can be gathered by sc = next().charat(0)
Hello world
Code
In java you need to classify the class, the method inside the class and the print function in order to print a hello world program.
To compile a java program you an use pre built methods in the code editors/IDE’s or use following code in the terminal. Note: This is made in Linux, useage on other OS may differ.
Compile method
Output
|
|
The second method is to use extensions; VSCode provides the apt extensions to work in Java as in working in an IDE. To download it just go to the extensopns
Keywords in hello world
- public - the given function is available throughout the program
- static - the java method can be called without the need to instansiate a class
- void - returns no output
- main - main class
- class - class classname
- println - prints a line with a newline charecter given below
How a Java program is executed
Java is a compile time program and it is cross platform, unlike C which uses its compiler to convert the .c file into machine code, the Java compiler converts the given code to a byte code that is executed within the Java runtime environment or JRE. The JRE is supported on various platforms from servers to microcomputers.
Java code -> byte code -> program gets executed
Print methods
AS in total there are two printmethods in Java; there is the println version and the print version. The println version gets an empty line after the print statement where as the standard print version does not. However escape sequences do work on both the given cases.
Basic info about Java
Datatypes
Like C/C++ java needs variables to be declared in the code before executing anycode.
These are the available data types in Java
- boolean data type
- byte data type (8-bit int -128, 127)
- char data type
- short data type (16-bit int -32768, 32767)
- int data type (32-bit int -2147483648, 2147483647)
- long data type (64-bit int -9223372036854775808, 9223372036854775807)
- float data type
- double data type
Note: Whenever a floating point datatype is used java always interprets it as a double datatype.
Variables
The following is the syntax of declaring a variable in Java
|
|
Output
Once the data is initalised the value can be changed further in the program. Multiple variable can also be declared in the same line.
A string should be enclosed in double brackets while a charecter is always enclosed in single brackets. In Java the default datatype for integer is always int, for storing longer numbers long
must be used, however since Java automatically recognises it as a int a suffix of L
may be applied. Similar case for having float, the default datatype for java for storing floating point datatype is double
so a suffix of F
may be added at the end of the data provided in the variable. As shown above large numbers can also be formatted like numbers in real life, insted of commas, numbers can be formatted by underscores, the Java compiler interprets them as standard numbers.
Java has two type of datatypes in broad classifiction.
- Primative datatypes
- Reference datatypes
Java has the following primative datatypes
Datatype | Description |
---|---|
boolean | stores true/false value |
byte | stores an 8 bit int |
char | stores a charecter |
double | stores a decimal datatype (high precision) |
float | stores a decimal datatype (low precision) |
int | stores a 32 bit int |
long | stores a 64 bit int |
short | stores a 32 bit int |
Primitive datatypes are shown above where are reference datatyped are based on either prebuilt or user generated classes, an example is given below |
Output
|
|
Here the util. Date module is imported from the Java library to initiate the Date class. The new operator here dynamically allocates the memory and hence gives data to the variable.
Type casting
In some scenarios the datatype of the variable is needed to be changes to another variable, this is called as type casting.
Output
|
|
Strings
Strings are the reference datatypes wherein it is an array of charecters. A string in Java is created by defining it by String
before the name of the variable.
Similar like python, Java supports string formating with the help of the addition operator. Like C, strings in Java have to be contained with double quotes where as charecters in Java have to be contained in single quotes.
Escape sequences
A simple print function has limitations of what it can and what it connot print, in some cases some charecters might not get printed since they are reserved in the programming syntax like the new line ASCII charecter. To overcome this escape sequences are used wherein the all the ASCII operations can be performed by the use of the given combinaion of symbols.
Escape sequences | Description |
---|---|
' | Single quote |
" | Double quote |
\ | Backslash |
\r | Carriage return |
\n | Newline |
\f | Form feed |
\t | Horizontal tab |
\b | Backspace |
\ddd | Octal constant (ddd) |
\uxxxx | Hexadecimal constant (xxxx) |
Taking input from the user
There are two major ways the program can take input from the user. Method 1 - Use builtin function
Output
Method 2 - Use scanner class
|
|
Output
Its always a good practice to close the scanner object in this case it was scanObj
using the scanObj.close() method.
Comments
Logical control
The if-else statement
The user can control the flow of the program with the help of if-else statements.
Here is a code in action.
Output
|
|
Switch statements
A switch statement is a multiway Java logical operator. Succeding versions after Java 7 will also support strings as the condition. A break statement must be added after every case statement so that the program stops and does not executes all the sucessive statements. A default keyword can be added if the user wants to specify when and where the code must stop.
|
|
Output 1
Output 2
Ternary operators
The following program can also be performed with the help of ternary operators.
Output
|
|
Strings as an exception
Two strings cannot be compared using the ==
operator as they are a derived data type. Here is how you compare two strings.
|
|
Loops
There are three types of loops in Java and they are namely the
- for loop
- while loop
- do-while loop
The for loop and the while loop are entry-controlled loop where as the do-while loop is exit controlled loop.
For loop
Syntax for for loop
Output
A for loop can also be initialised in an infinite manner with the following template
While loop
Syntax for while loop
Output
|
|
Do-while
Syntax for do-while loop
For each loop
Now this is not a complety distinctive style of loop fowever its just an extension of a standard for loop. For each loop cycles through an array till the array gets completed.
Output
|
|
Break statements
A break statement can also be initialised within a loop to exit a loop whenever a condition is met.
Output
Continue statements
The continue statemtnt tells the loop in the code to execute again making the code within the loop below the continue statemtnt irrelavant if the condiiton is met
|
|
Output
Datatypes
Arrays
A array is a one dimentional complex data type which can store one type of data inside it. In Java the arrays are stored as an object and should be used with object functions to interact. Given below is a program of how to scan and print two arrays. Note that none of the packages are required to interact with the array, however these are requited to do system input and printing the array. The individual elements can be accessed with the array indexing starting from 0 to the last-1 element of the array.
|
|
Output
Multidimentional array
Multidimentional array are similar to the linear array the only difference being its an array inside another array, since its just a compound array all the features of the regalar array functions are applicable here also.
|
|
Output
Misc functions in the array
- length - the arrayName.length function returns an integer value of the array length whenever its called
Error handling
If an error is occuring inside the program and the programmer wants the error to be handled gracefully error handling must be implementd. To do this a try-catch method is used.
Here is the syntax on how to catch errors
// error catching to be written
Garbage collection
Unlike the OG of high level programming language like C or C++ java is equipped with a much more advanced automated garbage collecion which removes unwanted java variables when not in use.
String comparision
The string compare method can be used to compare two given strings, when both the strings are same the inbuilt function returns a 0 with a -ve or +ve number being returned if the two strings are not matching.
Working with classes
Working with classes or as its commonly known as object oriented programming is a method of programming where the program is built with classes which are just charecterisation of a much more complex data type with the inclusion of functions.
Things to know before attempting OOPS in Java
- Only the main function should contain th public attribute
- The package must be defined for inclusion of more than one class (including the main)
What are we going to do?
Here we have made a folder called test
which contains a java file jarjar.java
, hence in order to achive the output install Java 1.17 + make the same folder structure.
Basics of class
|
|
Constructors
|
|
Output
Note: The this
keyword can be used to direct the variable in the current class scope and not be declared globally.
Passing objects as parameters
The following code demonstrated how passing of objects as parameters works, the code also shows how method overloading/function overloading/constructor overloading.
|
|
Static methods
Static methods are called independent of the object and make a standalone function.
|
|
Output
|
|
Inheritance
Inheritance in programming languages refers to getting all the properties of the parent function plus some more extras. Note: Multiple inheritance in not supported in Java, however is supported using interfaces.
|
|
Output
Super builtin function
The super function calls the parent class constructor from the child class. The super function must always lie before any other statements in the child class constructor.
- Super to access constructor
|
|
Output
- Super in acessing values of parent class
|
|
Output
Abstract classes
Abstract classes are those chasses which contain abstract methods
- An abstract class must be declared with an abstract keyword.
- It can have abstract and non-abstract methods.
- It cannot be instantiated.
- It can have constructors and static methods also.
- It can have final methods which will force the subclass not to change the body of the method.
An abstract class is a subset of normal classes where only the bare minimum is implemented.
|
|
Output
Abstract methods
Abstract methods are those methods housed inside the classes which dont have any implementation or we can say “A method declared using the abstract keyword within an abstract class and does not have a definition”.
The syntax for abstract methods is as follows:
|
|
Interfaces
Within an abstract class we can still have normal non-abstract methods, with the use of interfaces we can completely remove the need of solid methods
Exception handling
Managing execptions or code errors in java can be handled in a more customizable way with the use of exception handling
- Components of try catch
- try - asks the code to execute and argument and hope it doesn’t spit out an error
- catch - handles the error in a user defined way
- finally - the final block in the code which gets executed no matter what
- Throw
The try catch is a system defined error handling snippet, with the throw keyword the user can customize the exception handling without an external library.
The throw exception works with tandem with the try, catch, finally.
An example of try catch can be found below
|
|
This can be further be changed into a custom error with the use of throw
keyword. The syntax can be simplified into being as throw new error
as seen in termwork 8.
packages In Java, a package is a way to organize and structure code. A package is a collection of related classes, interfaces, and other resources that are bundled together. Packages are used to group similar classes and interfaces, and to provide a unique namespace for them. This helps to prevent naming conflicts and makes it easier to maintain and reuse code.
Packages in Java are created using the package keyword, followed by the package name. For example:
|
|
This creates a package named mypackage in the com.example namespace.
To use a class or interface from a package, you must import it using the import keyword. For example:
|
|
This imports the List interface from the java.util package.
It’s also possible to use the * wildcard to import all the classes and interfaces from a package. For example:
|
|
This imports all the classes and interfaces from the java.util package.
Java has a set of built-in packages, known as the Java API, which provide a wide range of functionality for common tasks such as working with strings, lists, and dates. Additionally, developers can create their own custom packages.
It’s a good practice to group related classes and interfaces in packages, and to use appropriate package names that reflect the functionality of the classes and interfaces. This makes it easy to understand the purpose of the package and how to use the classes and interfaces it contains.