Java Syntax Made Simple

Cahit Barkin Ozer
10 min readJul 15, 2022

A comprehensive guide to understanding the language.

If you are already familiar with another programming language, this article will help you rapidly comprehend the Java syntax.
If you don’t know how to program, I recommend doing additional research, solving algorithm problems, and developing programs.

This is a summary of Java syntax. The object-oriented aspect of Java will not be covered in this article; instead, I want to write another one about it.

How does Java Works?

Java code files have the.java extension and are initially compiled to bytecodes with the.class extension. The bytecodes are then interpreted in the JVM (Java virtual machine) that is unique to each operating system. As a result, Java becomes “Write Once, Run Everywhere.” JVMs include the JRE (Java runtime environment), which is used to run Java programs. JDK (Java Development Kit), a library for developing Java applications, is included with JREs.

Because Java is an object-oriented language, you must create each function within a class (functions that belong to classes are called methods). The main method in the main class is where Java applications begin. The main() method must be in the Main class, and the program must begin with this method. A project that lacks a main() function cannot be executed.
If you’re new to programming and don’t understand what these terms represent, don’t worry; you’ll get it eventually. For the time being, only realize that the following structure is required to run a Java program.

public class Main{  public void main(String[] args){      //This is where program starts
}
}

Java Syntax

Java’s syntax is similar to C’s syntax because it is developed to be a better version of c++. All the problematic features of c++ are removed and pointer operations are kept in the background, concurrency is simplified. I will not explain concurrency in this article you can check my java threading article: https://medium.com/@cbarkinozer/java-threading-32ac5f8c9423

Variables

In java, there are reference types and primitive types.

Primitive types

Following are primitive types sorted by their size: long>int>short>byte. There are also float double boolean and char.

int a=1;
long b=1;
short c=1;
byte d=1;
float e=1.2f;
double f=1.2;
boolean g=true;
char h=’A’;
char i=’\u0152';

In general, the integer is chosen. When converting an integer number to a double, long is preferable. For restricted integer values, short is desirable. Byte data is 8 bits long (-128,127). A bit is a binary value that can be either 1 or 0. The float contains floating points. Do not keep precise value (has a precision error). Double is generally favored over float since it is more exact. True(1) and false(1) binary data encoded (0). For Unicode operations, Char is preferable. Use String for character operations. There are no unsigned values in Java. For monetary operations, use BigDecimal instead of double (due to accuracy mistake). Strings are reference types in Java, not basic types. Consider String to be words made up of chars. Strings are employed.

Use String for character operations. There are no unsigned values in java. For monetary operations do not use double (because of precision error) instead use BigDecimal. Strings are not primitive but reference types in Java. Think of String as words that are coming together from chars. Strings are not character arrays. They are immutable. Which means you cannot change them in their memory. But you can create new ones at new memory places. There is a garbage collector in Java that if it detects a memory place That is not reachable anymore (unbound with a variable), collects that memory.

Variable names must begin with a letter of the alphabet. You cannot assign keywords (words used in Java programming) to variables such as int, public, and so on. Try to use English variable names as well.

int value; //Defined a value. You must initialize before using it. value=10;  //The initialization

Comments

Comments are for you to explain your code and decisions. “//” is used for single-line comments, and “/**/” is used for multi-line comments.

Reference types

String str = new String(); //Defined a string named str
str= “Hello User”; //String initialized

Printing

To print something on a new line on the console in java you need to use the println() method inside the System.out package.

System.out.println(“You can write what you want it to print”); System.out.println(value); //Or you can just print a value System.out.println(str+value); //Printing values together

Getting Input from the User

System.in is used by Scanner (import java.util). nextInt() retrieves the next int, nextLine() retrieves the next string, and next() retrieves the next non-space value. You can also read any other basic type.

Scanner scanner = new Scanner(System.in); 
int var = scanner.nextInt();

Arithmetic Operations

Arithmetic operation symbols are used to perform operations on variables.

int value=10;
int value2=5;
value= value + value2;
value = value - value2;
value= value * value2;
value = value / value2;
value = value % value2; //Reminder op. divides,and gets the reminder

There are certain shortcuts available for arithmetic operations performed on the same variable.

a=a+1;//Also can be done like following
a+=1; //Also like this
a++; //postfix
//Or (they are same unless we use them on the same line together)
++a; //prefix

Consider the prefix to be incrementing and obtaining the value, and the postfix to be getting and incrementing the value. These shortcuts also apply to other operations.

a-=1;
a*=1;
a/=1;

Math Class

You may utilize the Math class to do more complicated arithmetic operations. You do not need to import this package; it is automatically imported. You may use min(x,y), max(x,y), sqrt(x), abs(x), and other functions.

System.err.println(Integer.MIN_VALUE); //-2³¹ (~-2million) System.err.println(Integer.MAX_VALUE); //2³¹ — 1 (~2million)

Math.random() generates a number between 0.0 and 1.0; to generate a random value between 0–10, use the following code:

int randomInt = (int)(Math.random() * 11);  // 0 to 10

The “+” operation also does string concatenation.

str="Welcome to";
str=str+”Java”; // str is now has "Welcome to Java"

You may use special instructions within strings to execute a variety of functions. For example, \t stands for tab and \n stands for new line.

System.out.println(str);
System.out.println(“\n”+str+”\n”);

Integer != int. Java is case sensitive and these primitive named classes are wrapper classes. They are reference types that represent primitive types. These reference types also include methods that programmers may utilize.

When you perform an arithmetic operation on two different primitive types, the outcome is the type of the bigger type.

short j=1000;
int k= (j/2);

Because the translated type contains more space than the original type, there is no data loss.

double value1 = 2.5;int value2 = value1;//error
int value2 = (int)(value1); //valid and 2

Java does not convert automatically since data loss is likely, but you can do it yourself (by accepting the possible value loss).

Changing variable’s values

To exchange the values of two variables:

int temp=0;
int var1=10;
int var2=20;
temp=var1;
var1=var2;
var2=temp;

Conditional state structures (if, else if, else)

if(scanner.hasNextLine()){ //If scanner has next value
String string = new String();
string=scanner.nextLine();
System.out.println(“You entered following String:”+ string);
}else{
System.out.println(“Please enter a String”);
}

Keep in mind that if the value in “if” skips 0, “if” will not run. Floating points, such as float and double, cannot have the same value. Precision issues exist with float and double. If(double == 2.5) should not be used. You can choose between greater > and smaller symbols.

The String value cannot be equal because the == operation checks to see if they are in the same memory location. You must use str.equals() or str.equalsIgnoreCase(), which are String specified methods. “abc”==”abc” is acceptable. str1==str2 is not true.

For Loop

int i=0; generates an integer, which is commonly referred to as i which stands for index. The second portion is the stopping condition i<10, which terminates the loop if i is equal to 10. The final section describes the ongoing activity, which might be increments, decrements, etc.

for(int i=0;i<10;i++){ //Generally "i" is used as index
if(i%2==0){
continue;
}
System.out.println("Hello floppa"+i);
if(i==7){
break;
}
}

While Loop

While loop is repeated until the condition inside the parentheses is false.

int variable3 =0;
while (variable3 <10){
variable3++;
}
//Or
while (variable3 !=0){
variable3 — ;
}

Do-While Loop

Do-while executes the code within it first, then verifies the condition within the “while.” The sole difference between do-while and while is the extra run at the start.

 int until=0;
do{
until++;
}while(until !=10);

Switch-Case

If you do not add “break” after “case 2” for example, it will also run the “case 3". So you need to be careful for “break”s when using a switch case.

int door = 2;
switch (door) {
case 1:
System.out.println(“1. door Mr. Gill”);
break;
case 2:
System.out.println(“2. door Mrs. Roy”);
break;
case 3:
System.out.println(“3. door Mr. Jenkins”);
break;
default:
continue;
}

There are two commands: “break” and “continue.” The word “break” may be seen in the switch-case structure above. The “Break” interrupts the decision framework. Continue to bypass that loop. You may also specify a label and then jump to it. Taking a rest. These break and continue structures are rarely used since they are prone to errors.

Arrays

A series of values of the same kind are successively stored in memory. Because these values are stored immediately next to one other in memory, arrays really point to the array’s initial item (array[0]).

int[] array = new array[5]; //Creates 5 integer values (you can not change it's size)
int[] array2 = {1,2,3,4,5}; //Initializing it's values while creating
array2[0]=2; //Changing the first element of array

The index numbers are (0,1,2,3,4). Caution: be cautious of the indices. Indexes begin at zero and go to size-1 (since the mathematical sequence is n, n+1, n+2).

Attempting to access a value outside of the bounds will result in a “outOfBoundaries” error. It is fairly prevalent when using arrays, so be cautious. A loop may be used to add or alter all of the values in an array.

for(int i=0;i<5;i++){
array2[i]=i+1; //Increases every value by 1
}
for(int i=0;i<array2.length;i++){ //Checks length every time loop runs
array2[i]=i+1;
}

You can sort an array using the sort method in Arrays library in java.util.Arrays . It is an implementation of QuickSort algorithm.

Arrays.sort(array2);

int[] array1 = {1,2,3,4,5};
int[] array2 = {1,2,3,4,5};

You can not check the equality of arrays using “==” because it checks the memory address's equality (same as String equality checking).

if(array1==array2){ //Prints Not equal
System.out.println(“Equal”);
}else{
System.out.println(“Not equal”);
}

Instead use equals() method in Arrays.

if(Arrays.equals(array1,array2)){ //Prints Equal
System.out.println(“Equal”);
}else{
System.out.println(“Not equal”);
}

Multidimensional arrays

Multidimensional arrays are arrays inside arrays. Each element of the array stores another array and there is no limit to dimensions.

int[] array = new array[2][2]; //Creates 2 row 2 column matrix(2d array)
int[] array1 = {{1,2},{3,4}}; //Initializing a matrix (2 arrays inside an array)

To reach values nested for-loops are used:


for(int i=0;i<5;i++){ //For every arrray inside the array
for(int j=0;j<5;j++){ //For values inside the array
array2[i][j]=j+1; //Increases every value by 1
}
}

If you are not going to perform index operations on an array (for example just printing values), you can use the for-each loop. There is a for each loop mentality in programming languages, in java, this is performed as follows:

for(Integer i: array2){ //For every integer i in array2
System.out.println(i); //Print every value
}

This is also useful for object arrays.
Let’s assume we have:


public Account{
private String name; //attribute
Account(String name){ //constructor
this.name=name;
}
}
… (assume following are inside the main function)
Account[] accountArray={new Account(“account_name1”),new Account(“account_name1”), new Account(“account_name1”)};
for(Account account: accountArray){
System.out.println(account);
}

It prints the following:


account_name1
account_name2
account_name3

ArrayList

The ArrayList class is a resizable array with predefined useful methods in the java.util.package.

ArrayList<String> arrList = new ArrayList<String>(); //You need to give reference type, you can use wrapper classes (e.g Integer) not primitive (e.g int)
arrList.add(“Heartmachine”); //Adding value
arrList.add(“Echo chamber”);
arrList.add(“Sleepless”);
arrList.add(“Sleepless”); //There can be many amount of same values

System.out.println(arrList.get(0)); //Gets value
System.out.println(arrList.size()); //Gets size
System.out.println(arrList.indexOf(“Sleepless”)); //Gets index (2)
System.out.println(arrList.lastIndexOf(“Sleepless”)); //Gets the last Sleepless’ index (3)
System.out.println(arrList.indexOf(“Rot”)); // There are no Rot so returns -1

arrList.remove(“Echo chamber”); //Deletes element
arrList.set(2,”Impulse”); //Change 2. element with Impulse

There are more collections in Java, you can check my more detailed article that is about Java Collections:

https://medium.com/@cbarkinozer/collections-in-java-ec0a22fbc25e

Boxing, unboxing, and autoboxing

Wrapper classes are the most basic forms of reference versions (e.g in ArrayLists). Boxing is evolving from a primitive type to a wrapper class. And unpacking is the inverse process. Autoboxing is boxing performed by the Java compiler (automatically).

ArrayList<Integer> aList = new ArrayList<Integer>();
int num=0;
for(int j=0;j<aList.size();j++){
aList.add(Integer.valueOf(j*4)); //Boxing
num=aList.get(j); //Unboxing
aList.add(j*4); //Autoboxing
}

String

Strings are value references. They include handy preset methods. Following is not the same as warning.

//Creates a new String in memory that has "Hello Java"( or a variable)
String string= new String("Hello Java");
//adds a String that has "Hello Java" to string constant pool.
String str="Hello Java";
//points str2 in the string constant pool because they have the same value.
String str2="Hello Java";

But don’t worry, Strings are unchangeable ( if you change what is inside, it deletes that memory and creates a new variable).

if(str==str2){} //Returns true because they point the same memory
if(string==str){} //Returns false because they do not point the same memory
if(string.equals(str)){}//Now returns true

Some of the useful String methods

 str.isEmpty(); //Returns boolean if it is empty
str.charAt(0);//Prints “H”
str.charAt(str.length()-1); //Prints last element, “a”
str.startsWith(“He”); //Returns true
str.endsWith(“va”); //Returns true
str.toUpperCase();
str.toLowerCase();

//Warning: you need to assign these “to” methods if you want to save them.
str=str.toUpperCase();

String str1=”1234";
//String to integer
int number= Integer.parseInt(str1);

//Integer to String
int num=1234;
str1=String.valueOf(num);

LinkedList

Structures that are useful for inserting and deleting items between values without changing any values (low complexity for these operations). However, this is undesirable since each node also has a reference. If memory is critical, use ArrayList. A linked list is made up of nodes, each of which has a data field and a reference (link) to the next node in the list.

LinkedList<String> lList = new LinkedList<String>();
//Predefined methods are same as in the ArrayLists

Iterators

Iterators are objects that help us easily iterate values with predefined methods.

ListIterator<String> it = new ListIterator<String>();
while(it.hasNext()){ //Iterates all
System.out.println(iterator.next()); //prints the next value
}
//You can also go reverse using hasPrevious() and previous() methods.

Packages

Java has a large number of packages. These packages have methods that you may utilize. All you have to do is import them. To use Scanner, for example, you must first import:

import java.util.*;

The asterisk(*) sign denotes all classes contained inside that package. Java verifies which classes are being used and only imports those, so you don’t have to worry. On the other hand, specifically writing your import is a smart practice.

Java Naming Conventions

When developing Java code, you must follow to certain naming standards. English names must be used, and these names must be meaningful. The “camelCase” naming is applied for methods and variables. Classes, on the other hand, are named “PascalCase.”

public Account{
public getAccountCount(){
int accountCount = 5; return accountCount;
}
}

Please do not forget to clap if you enjoyed my article. Thank you.

You can also check the Advanced Java features article:

[Coming Soon]

--

--

Cahit Barkin Ozer

Daha fazla şey öğrenmek ve daha iyi olmak isteyen bir yazılım mühendisi.