Hello, and welcome to the third instalment of the blog series "The DSA Handbook". I'll go over the fundamentals of Java, including input/output, debugging, and datatypes, in this post. In addition, I'll discuss how to create your First Java Program, as the article's title states.
I picked up these ideas by watching the incredible YouTube playlist "Java + DSA + Interview Preparation Course" by Kunal Kushwaha
Let's begin now.
Structure of Java File
In Java, each source file contains a single public class or interface. The name of the source file must be the same as the name of the public class or interface it contains, with a .java extension.
A typical Java file has the following structure:
Package Declaration: At the top of the file, you can specify the package that the class belongs to using the
package
keyword.Import Statements: After the package declaration, you can import any classes or interfaces that the class uses from other packages using the
import
keyword.Class or Interface Declaration: Next, you declare the class or interface that the file contains. The class or interface must have the same name as the file and can be declared as public or default.
Fields: Fields are variables that belong to the class and store the state of the object.
Methods: Methods are functions that can be called on the object and perform some operations.
Constructors: Constructors are special methods that are used to create and initialize new objects of the class.
Here's an example of a simple Java class:
package com.example;
import java.util.ArrayList;
public class MyClass {
private intmyField;
private ArrayList<String> myList;
public MyClass() {
myField = 0;
myList = newArrayList<String>();
}
public void myMethod() {
// code to perform some operation
}
}
In this example, the class MyClass
is declared in the package com.example
and it imports the ArrayList
class from the java.util
package. The class has two fields myField
and myList
and one constructor and one method myMethod()
.
The "Hello World" Program
public class Main {
public static void main(String [] args) {
System.out.println("Hello World");
}
}
Now we'll go through each of the words you see here one by one. And I'll explain what they are in layman's terms. Don't worry if you don't get them right. When I write a blog explaining all of the OOPs concepts in Java, I will go over them in depth. Let's start with this for now.
public (First Line): public is an access modifier that allows our Main class to be accessed from anywhere in our code.
class: It is just a name group of properties and functions.
Main: It is just the name of the class which is the same as the name of the file (Main.java).
public (Second Line): It is used to allow the program to use the 'main function' (not the Main function) from anywhere.
static: We use static to run the 'main function' without creating any object of the 'Main class'.
void: It is a keyword used when we do not want to return anything from a method/function.
main: It is the name of the method. It is the entry part of the java program, from where the program starts.
String [] args: It is a command line argument of a string-type array.
Datatypes
In Java, data types are used to define the type of a variable or a constant, and determine the size and layout of the variable's memory.
There are two types of data types in Java:
Primitive Data Types: These are the basic data types that are built-in to the Java language and are not objects. They include:
int: Integer type, used for whole numbers.
long: Long integer type, used for larger whole numbers.
short: Short integer type, used for smaller whole numbers.
byte: Byte integer type, used for very small whole numbers.
float: Single-precision floating-point number.
double: Double-precision floating-point number.
boolean: Boolean type, used for true/false values.
char: Character type, used for single characters.
Non-Primitive Data Types: These are the advanced data types that are created by the programmer or provided as part of the Java class library. They include:
String: A sequence of characters.
Array: A collection of similar data types.
Class: A blueprint for an object.
Interface: A blueprint for a class.
Enumeration: A fixed set of values.
Java is a strongly-typed language, which means that every variable must have a specific data type, and that type cannot be changed during the execution of the program. For example, you cannot assign a string value to a variable of type int.
It's important to choose the right data type when you declare a variable to ensure that the variable has enough memory to store the value and that the value is stored in the appropriate format.
Type Casting
When one type of data is assigned to another type of variable, an automatic type conversion will take place under some condition. This is called Type Conversion.
Conditions:
Two types should be compatible.
Destination type should be greater than source type i.e. whatever data type you've on the left side should be greater than the data type on right hand side.
float num = input.nextInt();
Asking something bigger like 'float' but user is giving something smaller like 'int', it will work.
When we convert one datatype to another datatype it is called Type Casting.
int num = (int)(678.544f);
// This will only give the integer value of the literal.
Basically the automatic type conversion does many things but when we need to convert some bigger data type (float) to the smaller data type (int), we do it manually And it is called Narrow Conversion (Narrowing the data type).
The automatic type conversion will convert the input integer (12) to a float value (12.0). But if input is given as (12.2), it will give an error.
Automatic Type promotion in Expression
While evaluating expression, the intermediate value may exceed the range of operands & hence the expression value will be promoted.
Conditions:
Java automatically promotes each byte, short or char operands to int when evaluating an expression.
If one operand is a long, float or double, the whole expression is promoted to long, float or double.
byte a = 100;
byte b = 50;
int c = (a*b);
System.out.println(c);
The output of this will be 2000.
Thorough example of everything:
byte b = 42;
char c = 'a';
Short s = 1024;
int i = 50000;
float f = 5.67f;
double d = 0.1234;
double result = (f*b) + (i/c) - (d*s);
// double = float + int - double
System.out.println(result);
The output of this will be 626.7784146484375
(f*b) --> Gives 'float' value because 'float' is a bigger value than 'bytes'.
(i/c) --> Gives 'integer' value because 'integer' is a bigger value than the 'ascii code of characters'.
(d*s) --> Gives 'double' value because 'double' is a bigger value than 'short'.
And the result will give the value as 'double' because among float, integer and double, double is the bigger data type. This is called Automatic Type Promotion in Expression.
Output in Java
In Java, you can use the System.out.print()
or System.out.println()
method to output text to the console. The print()
method will output the text without a newline character at the end, while the println()
method will output the text with a newline character at the end.
Here is an example of how to use the System.out.println()
method to output a message to the console:
public class Main {
public static void main(String [] args) {
System.out.println("Hello, world!");
}
}
In this example, we use the println()
method to output the string "Hello, world!" to the console. You can also use the print()
method to output text to the console like this:
System.out.print("Hello, ");
System.out.print("world!");
This will output "Hello, world!" in the same line.
You can also use printf()
method for formatted output.
System.out.printf("My name is %s and I am %d years old", "Bob", 30);
This will output "My name is Bob and I am 30 years old"
You can also use +
operator to concatenate strings and other type of data and display as output.
System.out.println("My name is " + name + " and I am " + age + " years old");
Now we'll go through each of the words you see here one by one
The System here is a class that contains several useful class fields and methods.
out is a variable of type PrintStream.
And PrintStream has some object called Println.
In short, the 'System' has a variable called 'out' which is of type PrintStream, has a method called 'Println'.
Input in Java
In Java, you can use the Scanner
class to take input from the user. Here is an example of how to use the Scanner
class to take input from the user and store it in a variable:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = input.nextInt();
System.out.println("You entered: " + num);
}
}
In this example, we first import the Scanner
class using the import
keyword. Then, we create a new Scanner
object named input
that reads input from System.in
, which is the standard input stream. We then use the nextInt()
method of the Scanner
class to read an integer from the user and store it in the variable num
. Finally, we print the value of num
to the console to confirm that the input was read correctly.
You can also use nextLine()
method to take String input and nextFloat()
for taking float input.
Conclusion
I've covered some of the basics of Java, including datatypes, input, and output. Understanding these concepts is crucial for writing Java programs. We've also discussed the structure of Java files, and how the package, import, class, fields, methods, and constructors are used.
As I continue to learn and grow, there will be many more concepts to discover and explore. However, with a solid understanding of the basics, you will be well-equipped to tackle more advanced topics. I will be uploading more Java related articles as I learn new concepts, so stay tuned for more updates and insights on this exciting programming language.