This Article for JAVA beginners.
Introduction
I will discuss about java basics with that article series. i have plan to cover java basics concepts with three article. in This is first article in this article series. i discuss about Syntax, Output, Input, Data types, Variables, Comments, Try /catch, Operators, Strings, Math, and Booleans in this article. i will discuss these concepts clearly.
Before Start java Syntax. i have plan to discuss about how write code lines correctly and what are the rules in the java coding.
In the java we should use semicolon(;) for end of the all lines.
Example:
// I not have write java main syntax here. i will discuss in below. // if you went to run this code and check it. you can read syntax section and run this code System.out.println("Hello world") <---- This not correct System.out.println("Hello world"); <---- This correct ^ | Semicolon(;)
First code line not have semicolon(;) so it is incorrect. if you run this code java engine will display error.
Second code line have semicolon(;) so it is correct. (it work perfectly).
How use curly brackets correctly
why curly brackets?
Curly brackets are the area of residence of the statement or loop. simply if you use if statement it limitation area will display with Curly brackets.
Example:
How to create java class
you have create .java file with same to the class name.
class my{ ^ | java file name is my.java }
Syntax
If went learn java you should first learn main syntax in java
Why main syntax?
The main method is the first method of the java and it is the entry point of the executing code. The main method can contain code to execute or call other methods, and it can be placed in any class that's part of a program.
(Digitalocen,nodate)
Main Method
public class Main(){ public static void main(String[] args){ // your code here System.out.println("Hello world") } }
According to the above code it is the main method of the java. if went to code java, you will need call main method for the execute your code. please remember that main method. you will need that main syntax for coding.
Practice your code with below replit
fork that replit and practice it.
output
if you went print some output in java you can use System.out.print()
commad. inside the parentheses you can write what you need to get output. example is you went to print ''Hello world'' you can write it like below
Example one:
- Remember if you went print work or some sentence with java you should write your world inside the comma or double comma.
// words or senteces outputs
class Main{
public static void main(String[] args){
System.out.print("Hello world"); //output is Hello word
}
}
Example two:
// numbers outputs
class Main{
public static void main(String[] args){
System.out.print(23); //output is 23
}
}
print Vs println
if you use print()
commad it does not insert a new line at the end of the output
Example is
class Main{
public static void main(String[] args){
System.out.print(23);
System.out.print(49);
System.out.print(52);
}
}
// The output is: 235952
if you use println()
commad it does insert a new line at the end of the output
class Main{
public static void main(String[] args){
System.out.println(23);
System.out.println(49);
System.out.println(52);
}
}
// The output is: 23
49
52
You can try it your self with below replit
Data Types
We can identify some data types in the java it can classification to two types it is primitive datatypes and non-primitive datatypes
primitive data types are:
byte, short, int, long, float, double, boolean and char
non-primitive data types are:
String
Variables
what is variable ? variable is a symbolic name for an unknown quantity. we can store some values with variable and we can use that variable when we needed. we almost many time use variable in the programming. it is the most import concept.
How to create variable? in the blow have syntax for the make variable.
Data_type var_name = value;
<-- Assigning the value at the same time as the variable is created
example: int num = 10;
Data_type var_name;
<-- only created variable. assign value later
example: int num;
num = 10;
first have declare data type, for it you can use which you need data type. and also you can give any name for variable name, but for it have some rules. i will discuss it below.
Input
For get inputs we need use one package in java. it name is Scanner package. in below i will discuss how use that package
First we need import Scanner package for the our code for it we use import java.util.Scanner;
After import that package we can get inputs from the CMD interface. in the below i have provide step for it.
Step 1 - Import Package
import java.util.Scanner;
Step 2 - Create main method
import java.util.Scanner;
class Main{
public static void main(String[] args){
}
}
Step 3 - Declare variable for store input data
First need create Scanner object for the use Scanner package
example:
Scanner sc = new Scanner(System.in)
For catch String with Scanner class we need call
next()
objectexample:
sc.next()
Other Scanner objects discuss later with example and tasks.
After store that data with variable
Example:
import java.util.Scanner;
class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in); <-- Create Scanner Object
String name;
System.out.println("Enter your name: ");
name = sc.next(); <-- catch data and store it to name variable
System.out.println(name);
}
}
You can practice this with below replit
Comments
Single line comments
// single line comment heree
Multi-line comments
/*
Multi line comments here
*/
Try/Catch
The Try Catch in java statements allows you to define a block of code to be tested for exceptions (errors) while it is being executed. The Try Catch in Java always occurs in pairs; the catch statement allows you to define a block of code to be executed, if an error occurs in the try block(Simplilearn,2023)
we can identify some benefits if we use try/catch it is,
it help to write code flawless.
We can identify error easily.
it reduce code crashing.
easy to flow control
syntax of the try /catch:
try{
//your code
}catch(Exception e){
System.out.println(error)
}
Example one:
import java.util.Scanner;
class Main{
public static void main(String[] args) {
int name; //<-- this variable is integer
Scanner sc = new Scanner(System.in);
System.out.println("Enter your name: "); //<-- get name(name is string value)
try { // try statement start
name = sc.nextInt(); //<-- try to string value to int variable(it can't do)
} catch (Exception e) { //<-- catch statement catch error and store it to e variable
System.out.println(e + " -------Have Error "); //<-- print error here
}
System.out.println("Done"); //<-- program execute success without exit
}
}
you can practice try catch below replit
if you have get error you can search that error google, and find solution for it. it will grow your coding knowledge. if you not have find solution from google you can email me.
additionally you can search your error these websites:
Operators
operators are use for different operations on variables and values
operators are mainly four type it is,
Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Arithmetic Operators
practice that arithmetic operators below replit
Comparison Operators
Assignment operators
This is are assignment operators it is used for assign values for to the variable.
Logical operators
you can practice that logical operators with that replit
String
String is a a sequence of characters. a character , word , sentence or any collection of sentences belongs to String type.
we can identify some string operations in the java. in the below discuss it clearly
How create String variable?
- Syntax is :
String var_name = "Value";
String methods
.length()
method
class Main{
public static void main(String[] args) {
String txt = "I am Dineth, I am from Sri Lanka";
System.out.println("Length is: " + txt.length() );
}
}
//output is: Length is: 32
.toUpperCase()
method
class Main{
public static void main(String[] args) {
String txt = "I am Dineth, I am from Sri Lanka";
System.out.println(txt.toUpperCase());
}
}
// output is: I AM DINETH, I AM FROM SRI LANKA
.toLowerCase()
method
class Main{
public static void main(String[] args) {
String txt = "I am Dineth, I am from Sri Lanka";
System.out.println(txt.toLowerCase());
}
}
// output is: i am dineth, i am from sri lanka
String Index
.indexOf() method
class Main{
public static void main(String[] args) {
String txt = "CODESPEEDY";
System.out.println(txt.indexOf("C"));
}
}
// output is: 0
String concatenation
class Main{
public static void main(String[] args) {
String txt = "Happy";
String pt = "Coding";
System.out.println(txt + pt);
}
}
//output is: HappyCoding
class Main{
public static void main(String[] args) {
String txt = "Happy";
String pt = "Coding";
System.out.println(txt + " " + pt); // i have add space to the middle of the txt and pt
}
}
// i have use \n for get pt text to new line.
// if you went add new line you can use \n.
// \n alway provide new line.
class Main{
public static void main(String[] args) {
String txt = "Happy";
String pt = "Coding";
System.out.println(txt + "\n" + pt);
//ex2
System.out.println("Frist sentences. Second sentence. Tired sencente");
// above code output is: Frist sentences. Second sentence. Tired sencente
System.out.println("Frist sentences.\nSecond sentence.\nTired sencente");
// above code output is: Frist sentences.
// Second sentence.
// Tired sencente
}
Practice this with below replit
Special Characters
PROMBLEM
class Main{
public static void main(String[] args) {
String txt = 'I'm dient'; // <-- this is incorrect reason is you have write String value using Single quote
System.out.println(txt + pt);
}
}
Solution
solution one
class Main{ public static void main(String[] args) { String txt = "I'm dient"; // <-- can use double quote write String value System.out.println(txt + pt); } }
solution two
class Main{ public static void main(String[] args) { String txt = 'I\'m dient'; // <-- can use back slash for write value System.out.println(txt + pt); } }
Math
we can identify some math objects in java
Math.random()
method
you can generate random numbers with that method
public class Main {
public static void main(String[] args) {
System.out.println(Math.random()); //output: 0.0565
System.out.println(Math.random()*100); //output: 56.838
System.out.println((int)(Math.random()*100)); //output: 95
}
}
Math.max()
method
public class Main {
public static void main(String[] args) {
System.out.println(Math.max(20, 10)); //output: 20
}
}
Math.min()
method
public class Main {
public static void main(String[] args) {
System.out.println(Math.min(2, 9)); //output: 2
}
}
Math.sqrt()
method (square root value)
public class Main {
public static void main(String[] args) {
System.out.println(Math.sqrt(16)); //output: 4
}
}
Math.abs()
method (absolute value)
public class Main {
public static void main(String[] args) {
System.out.println(Math.abs(-5.2)); //output: 5.2
}
}
Exercises
1. Data Types and Variables:
Create a Java program that asks the user for their name, age, and favorite color. Store this information in appropriate data types and then print it back to the console.
Sample Output:
What is your name? Alice
How old are you? 25
What is your favorite color? Blue
Output should be: Hello, Alice! You are 25 years old and your favorite color is blue.
2. Input and Comments:
Write a Java program that takes an integer input from the user and calculates and prints the factorial of that number. Use comments to explain the code.
Sample Output:
- Enter a non-negative integer: 5
Output should be: Factorial of 5 is 120
3. Operators and Strings:
Develop a Java program that takes two strings from the user and concatenates them. Print the concatenated string along with its length.
Sample Output:
Enter the first string: Hello
Enter the second string: World
Outputs should be:
Concatenated string: HelloWorld
Length of the concatenated string: 10
Write Java program for that three exercises and email me
my email: djanithak@gmail.com
I hope you have get knowledge with that article. if you have see any doute points in this article you can kindly email me that point. i will make correct that points. And also kindly email me if there is anything you don't understand in this article.