Knowledge in Java

Switch in Java

SwitchThe switch statement can be used to handle several alternatives if they are based on the same constant value.switch (expression) { case constant1: command; break; // will prevent that the other cases or also executed case constant2: command; break; ... default: } // Example: switch (cat.getLevel()) { case 0: return true; case 1: if (cat.getLevel() == 1) { if (cat.getName().equalsIgnoreCase(req.getCategory())) { return true; } } case 2: if (cat.getName().equalsIgnoreCase(req.getSubCategory())) { return true; } } // you can also use the same logic for different constants public static void main(String[] args) { for (int i = 0; i < 6; i++) { switch (i) { case 1: case 5: System.out.println("Hello"); break; default: System.out.println("Default"); break; } } } }

Base Java language structure

Base Java language structure1)ClassA class is a template that describes the data and behavior associated with an instance of that class.A class is defined by the class keyword and must start with a capital letter. The body of a class is surrounded by {}.package test; class MyClass { } The data associated with a class is stored in variables ; the behavior associated to a class or object is implemented withmethods.A class is contained in a text file with the same name as the class plus the .java extension. It is also possible to define inner classes, these are classes defined within another class, in this case you do not need a separate file for this class2)ObjectAn object is an instance of a class.The object is the real element which has data and can perform actions. Each object is created based on the class definition. The class can be seen as the blueprint of an object, i.e., it describes how an object is created.

History of Java

James Gosling initiated Java language project in June 1991 for use in one of his many settop box projects. The language, initially called ‘Oak’ after an oak tree that stood outside Gosling's office, also went by the name ‘Green’ and ended up later being renamed as Java, from a list of random words. Sun released the first public implementation as Java 1.0 in 1995. It promised Write Once, Run Anywhere (WORA), providing no-cost run-times on popular platforms. On 13 November, 2006, Sun released much of Java as free and open source software under the terms of the GNU General Public License (GPL). On 8 May, 2007, Sun finished the process, making all of Java's core code free and opensource, aside from a small portion of code to which Sun did not hold the copyright. Tools You Will Need For performing the examples discussed in this tutorial, you will need a Pentium 200-MHz computer with a minimum of 64 MB of RAM (128 MB of RAM recommended). You will also need the following softwares: Linux 7.1 or Windows xp/7/8 operating system Java JDK 8 Microsoft Notepad or any other text editor This tutorial will provide the necessary skills to create GUI, networking, and web applications using Java. Java 4 Try It Option We have provided you with an option to compile and execute available code online. Just click the Try it button avaiable at the top-right corner of the code window to compile and execute the available code. The

Basic Syntax of java

When we consider a Java program, it can be defined as a collection of objects that communicate via invoking each other's methods. Let us now briefly look into what do class, object, methods, and instance variables mean.  Object - Objects have states and behaviors. Example: A dog has states - color, name, breed as well as behavior such as wagging their tail, barking, eating. An object is an instance of a class. Class - A class can be defined as a template/blueprint that describes the behavior/state that the object of its type supports. Methods - A method is basically a behavior. A class can contain many methods. It is in methods where the logics are written, data is manipulated and all the actions are executed. Instance Variables - Each object has its unique set of instance variables. An object's state is created by the values assigned to these instance variables. First Java Program Let us look at a simple code that will print the words Hello World. public class MyFirstJavaProgram { /* This is my first java program. * This will print 'Hello World' as the output */ public static void main(String []args) { System.out.println("Hello World"); // prints Hello World } } Let's look at how to save the file, compile, and run the program. Please follow the subsequent steps: Open notepad and add the code as above. Save the file as: MyFirstJavaProgram.java. Open a command prompt window and go to the directory where you saved the class. Assume it's C:\. 3. Java – Basic Syntax Java 8 Type 'javac MyFirstJavaProgram.java' and press enter to compile your code. If there are no errors in your code, the command prompt will take you to the next line (Assumption : The path variable is set).  Now, type ' java MyFirstJavaProgram ' to run your program. You will be able to see ' Hello World ' printed on the window. C:\> javac MyFirstJavaProgram.java C:\> java MyFirstJavaProgram Hello World Basic Syntax About Java programs, it is very important to keep in mind the following points. Case Sensitivity - Java is case sensitive, which means identifier Helloand hello would have different meaning in Java. Class Names - For all class names the first letter should be in Upper Case. If several words are used to form a name of the class, each inner word's first letter should be in Upper Case. Example: class MyFirstJavaClass Method Names - All method names should start with a Lower Case letter. If several words are used to form the name of the method, then each inner word's first letter should be in Upper Case. Example: public void myMethodName() Program File Name - Name of the program file should exactly match the class name. When saving the file, you should save it using the class name (Remember Java is case sensitive) and append '.java' to the end of the name (if the file name and the class name do not match, your program will not compile). Example: Assume 'MyFirstJavaProgram' is the class name. Then the file should be saved as 'MyFirstJavaProgram.java' public static void main(String args[]) - Java program processing starts from the main() method which is a mandatory part of every Java program. Java 9 Java Identifiers All Java components require names. Names used for classes, variables, and methods are called identifiers. In Java, there are several points to remember about identifiers. They are as follows: All identifiers should begin with a letter (A to Z or a to z), currency character ($) or an underscore (_). After the first character, identifiers can have any combination of characters. A key word cannot be used as an identifier. Most importantly, identifiers are case sensitive. Examples of legal identifiers: age, $salary, _value, __1_value. Examples of illegal identifiers: 123abc, -salary. Java Modifiers Like other languages, it is possible to modify classes, methods, etc., by using modifiers. There are two categories of modifiers: Access Modifiers: default, public , protected, private Non-access Modifiers: final, abstract, strictfp We will be looking into more details about modifiers in the next section.

Object And Class

Java is an Object-Oriented Language. As a language that has the Object-Oriented feature, Java supports the following fundamental concepts: Polymorphism Inheritance Encapsulation Abstraction Classes Objects Instance Method Message Parsing In this chapter, we will look into the concepts - Classes and Objects. Object - Objects have states and behaviors. Example: A dog has states - color, name, breed as well as behaviors – wagging the tail, barking, eating. An object is an instance of a class. Class - A class can be defined as a template/blueprint that describes the behavior/state that the object of its type support. Objects in Java Let us now look deep into what are objects. If we consider the real-world, we can find many objects around us, cars, dogs, humans, etc. All these objects have a state and a behavior. If we consider a dog, then its state is - name, breed, color, and the behavior is - barking, wagging the tail, running. If you compare the software object with a real-world object, they have very similar characteristics. Software objects also have a state and a behavior. A software object's state is stored in fields and behavior is shown via methods. So in software development, methods operate on the internal state of an object and the object-to-object communication is done via methods. 4. Java – Objects & Classes Java 14 Classes in Java A class is a blueprint from which individual objects are created. Following is a sample of a class. public class Dog{ String breed; int ageC String color; void barking(){ } void hungry(){ } void sleeping(){ } } A class can contain any of the following variable types. Local variables: Variables defined inside methods, constructors or blocks are called local variables. The variable will be declared and initialized within the method and the variable will be destroyed when the method has completed. Instance variables: Instance variables are variables within a class but outside any method. These variables are initialized when the class is instantiated. Instance variables can be accessed from inside any method, constructor or blocks of that particular class. Class variables: Class variables are variables declared within a class, outside any method, with the static keyword. A class can have any number of methods to access the value of various kinds of methods. In the above example, barking(), hungry() and sleeping() are methods. Following are some of the important topics that need to be discussed when looking into classes of the Java Language. Constructors When discussing about classes, one of the most important sub topic would be constructors. Every class has a constructor. If we do not explicitly write a constructor for a class, the Java compiler builds a default constructor for that class. Java 15 Each time a new object is created, at least one constructor will be invoked. The main rule of constructors is that they should have the same name as the class. A class can have more than one constructor. Following is an example of a constructor: public class Puppy{ public Puppy(){ } public Puppy(String name){ // This constructor has one parameter, name. } } Java also supports Singleton Classes where you would be able to create only one instance of a class. Note: We have two different types of constructors. We are going to discuss constructors in detail in the subsequent chapters. 

What is Java?

Java is a popular programming language, created in 1995.It is owned by Oracle, and more than 3 billion devices run Java.It is used for:Mobile applications (specially Android apps)Desktop applicationsWeb applicationsWeb servers and application serversGamesDatabase connectionAnd much, much more!

Why Use Java?

Why Use Java?Java works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc.)It is one of the most popular programming language in the worldIt is easy to learn and simple to useIt is open-source and freeIt is secure, fast and powerfulIt has a huge community support (tens of millions of developers)

Java Getting Started

Java InstallSome PCs might have Java already installed.To check if you have Java installed on a Windows PC, search in the start bar for Java or type the following in Command Prompt (cmd.exe):C:\Users\Your Name>java -versionIf Java is installed, you will see something like this (depending on version):java version "11.0.1" 2018-10-16 LTSJava(TM) SE Runtime Environment 18.9 (build 11.0.1+13-LTS)Java HotSpot(TM) 64-Bit Server VM 18.9 (build 11.0.1+13-LTS, mixed mode)If you do not have Java installed on your computer, you can download it for free from oracle.com.

Java Quickstart

Java QuickstartIn Java, every application begins with a class name, and that class must match the filename.Let's create our first Java file, called MyClass.java, which can be done in any text editor (like Notepad).The file should contain a "Hello World" message, which is written with the following code:MyClass.javapublic class MyClass { public static void main(String[] args) { System.out.println("Hello World"); } }

Java Quickstart 2

Don't worry if you don't understand the code above - we will discuss it in detail in later chapters. For now, focus on how to run the code above.Save the code in Notepad as "MyClass.java". Open Command Prompt (cmd.exe), navigate to the directory where you saved your file, and type "javac MyClass.java":C:\Users\Your Name>javac MyClass.javaThis will compile your code. If there are no errors in the code, the command prompt will take you to the next line. Now, type "java MyClass" to run the file:C:\Users\Your Name>java MyClassThe output should read:Hello Worldpublic class MyClass { public static void main(String[] args) { System.out.println("Hello World"); } } Output.C:\Users\Name\java MyClassHello World

Java Syntax

Java SyntaxIn the previous chapter, we created a Java file called MyClass.java, and we used the following code to print "Hello World" to the screen:MyClass.javapublic class MyClass { public static void main(String[] args) { System.out.println("Hello World"); } } Example explainedEvery line of code that runs in Java must be inside a class. In our example, we named the class MyClass. A class should always start with an uppercase first letter.Note: Java is case-sensitive: "MyClass" and "myclass" has different meaning.The name of the java file must match the class name. When saving the file, save it using the class name and add ".java" to the end of the filename. To run the example above on your computer, make sure that Java is properly installed: Go to the Get Started Chapter for how to install Java. The output should be:Hello World

The main Method

The main MethodThe main() method is required and you will see it in every Java program:public static void main(String[] args) Any code inside the main() method will be executed. You don't have to understand the keywords before and after main. You will get to know them bit by bit while reading this tutorial.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.System.out.println()Inside the main() method, we can use the println() method to print a line of text to the screen:public static void main(String[] args) { System.out.println("Hello World"); } Note: In Java, each code statement must end with a semicolon.Test Yourself With ExercisesExercise:Insert the missing part of the code below to output "Hello World".public class MyClass { public static void main(String[] args) { ..("Hello World"); } }