Hi All,
I will show you on the common syntax that we have to learn in Java.
For now, just remember that every Java program has a class
name which must match the filename, and that every program must contain the main()
method.
Variables (String, Int, Float, Char, Boolean)
public class MyVariables { public static void main(String[] args){ String name = "Shaharil"; System.out.println(name); int age = 35; System.out.println(age); float money = 613.10f; System.out.println(money); char myLetter = 'S'; System.out.println(myLetter); boolean myBool = true; System.out.println(myBool); String firstName = "Qaisara"; String secondName = "Shaharil"; String fullName = firstName + " " + secondName; System.out.println(fullName); } }
Control_Statement ( if, if-else if, while, for)
public class Control_Statements { public static void main(String[] args){ // if statement int x = 20; int y = 18; if(x>y){ System.out.println("X is greater than y"); } // if-else if statement int time = 20; if(time<18){ System.out.println("Good"); } else if (time == 20){ System.out.println("Normal"); } else{ System.out.println("Bad"); } // While statement int i = 0; while(i<5){ System.out.println(i); i++; } // For statement for(int k=0; k<5;k++){ System.out.println(k); } String[] cars = {"Volvo","BMW","Ford"}; for(String q:cars){ System.out.println(q); } } }
Array_examples
public class array_examples { public static void main(String[] args){ String[] cars = {"Volvo","BMW","Honda"}; System.out.println(cars[0]); System.out.println(cars.length); for(int i= 0;i<cars.length;i++){ System.out.println(cars[i]); } for(String q:cars){ System.out.println(q); } } }
Methods
A method is a block of code which only runs when it is called. You can pass data, known as parameters, into a method.
Methods are used to perform certain actions, and they are also known as functions.
Why use methods? To reuse code: define the code once, and use it many times.
public class method_examples { static void myMethod(){ // static means the myMethod below to class named method_examples // void that means this myMethod don't have a return value. System.out.println("I have learned method"); } static void myMethod2(String fname, int age){ System.out.println(fname + "Shaharil" + " " + age + " " + "years old"); } static int myMethod3(int x, int y){ // this method/function will return integer value return x + y; } static void checkAge(int Age){ if(Age<18){System.out.println("Access denied");} else{System.out.println("Access granted");} } public static void main(String[] args){ myMethod(); myMethod2("Qaisara" + " ", 2); System.out.println(myMethod3(5,3)); checkAge(20); } }