Java Programming Basics PDF
Document Details
KPR Institute of Engineering and Technology
Tags
Related
Summary
This document appears to be lecture notes on introductory Java programming. It covers fundamental OOP concepts like objects, classes, abstraction, encapsulation, inheritance, and polymorphism, along with the characteristics of Java and Java environments.
Full Transcript
Department of Computer Science and Engineering KPR Institute of Engineering and Technology ------------------------------------------------------------------------------------------------ B.E. – COMPUTER SCIENCE AND ENGINEERING COURSE MATERIAL...
Department of Computer Science and Engineering KPR Institute of Engineering and Technology ------------------------------------------------------------------------------------------------ B.E. – COMPUTER SCIENCE AND ENGINEERING COURSE MATERIAL U21CSG04 – JAVA PROGRAMMING (2023-2024: Odd Semester) ------------------------------------------------------------------------------------------------ PREPARED BY Dr. R. H. Aswathy, AP (Sl. G.) / CSE (Course Coordinator) Dr. M. Saravanan, AsP / CSE Dr. K. Kamaraj, AsP / CSE U21CSG04 – [UNIT I – OBJECT ORIENTED PROGRAMMING AND JAVA Java Programming BASICS] UNIT I: Object oriented programming-Concepts Abstraction-Encapsulation- Comparison with function oriented programming- Characteristics of Java – Java Environment- JVM and JDK – classes -constructors- methods-Static members-comments-Data types-Variables- Operator-Control flow 1. OOP – Object and Classes Object-oriented programming is a programming paradigm based on the concept of "objects", which can contain data and code: data in the form of fields, and code, in the form of procedures. Important/Core Concepts in OOPs Object Class Abstraction Encapsulation Inheritance Polymorphism Objects An entity that has state and behavior is known as an object e.g., chair, bike, marker, pen, table, car, etc. It can be physical or logical (tangible and intangible). The example of an intangible object is the banking system. An Object is an instance of a class An object has three characteristics: State: represents the data (value) of an object. Behavior: represents the behavior (functionality) of an object such as deposit, withdraw, etc. Identity: An object identity is typically implemented via a unique ID. The value of the ID is not visible to the external user. However, it is used internally by the JVM to identify each object uniquely. Prepared By: Dr. R. H. Aswathy, AP(Sl. G.) / CSE Department, KPRIET, Coimbatore. Page 1 U21CSG04 – [UNIT I – OBJECT ORIENTED PROGRAMMING AND JAVA Java Programming BASICS] Why OOPs Used to breaking down large problems into sub-problems and solving them in separate units of code Modularity for easier troubleshooting 2. Reuse of code through inheritance 3. Flexibility through polymorphism 4. Effective problem solving Class A class is a group of objects which have common properties. It is a template or blueprint from which objects are created. It is a logical entity. It can't be physical. Collection of objects is called class. It is a logical entity. A class can also be defined as a blueprint from which you can create an individual object. Class doesn't consume any space. A class in Java can contain: o Fields o Methods o Constructors o Blocks o Nested class and interface Prepared By: Dr. R. H. Aswathy, AP(Sl. G.) / CSE Department, KPRIET, Coimbatore. Page 2 U21CSG04 – [UNIT I – OBJECT ORIENTED PROGRAMMING AND JAVA Java Programming BASICS] Figure: Student Figure: Person Abstraction The abstraction is hiding the internal implementation and highlight the set of features offered. Prepared By: Dr. R. H. Aswathy, AP(Sl. G.) / CSE Department, KPRIET, Coimbatore. Page 3 U21CSG04 – [UNIT I – OBJECT ORIENTED PROGRAMMING AND JAVA Java Programming BASICS] Example: ATM Internal implementation – how each features work Features – Deposit, Withdraw, Balance enquiry Data Abstraction may also be defined as the process of identifying only the required characteristics of an object ignoring the irrelevant details. The properties and behaviors of an object differentiate it from other objects of similar type and also help in classifying/grouping the objects. Consider a real-life example of a man driving a car. The man only knows that pressing the accelerators will increase the speed of a car or applying brakes will stop the car, but he does not know about how on pressing the accelerator the speed is actually increasing, he does not know about the inner mechanism of the car or the implementation of the accelerator, brakes, etc in the car. This is what abstraction is. In java, abstraction is achieved by interfaces and abstract classes. We can achieve 100% abstraction using interfaces. Figure: Abstraction Encapsulation The process of binding of data and method together as a single unit The process of grouping of data members and corresponding methods into single unit Prepared By: Dr. R. H. Aswathy, AP(Sl. G.) / CSE Department, KPRIET, Coimbatore. Page 4 U21CSG04 – [UNIT I – OBJECT ORIENTED PROGRAMMING AND JAVA Java Programming BASICS] Data members →string name, int age, int rollno, int marks Methods→read(), write() Example 1: class student { string name; int age; int rollno; int marks; } read() { } write() { } Any component following data hiding and abstraction is called encapsulation Example 2: Class account { private double balance; { } public double getbalance() { return balance; Prepared By: Dr. R. H. Aswathy, AP(Sl. G.) / CSE Department, KPRIET, Coimbatore. Page 5 U21CSG04 – [UNIT I – OBJECT ORIENTED PROGRAMMING AND JAVA Java Programming BASICS] } public void setbalance(double amount) { this.balance = this.balance + amount; } NOTE: End user doesnot know the functionality, but the end user can perform withdraw and deposit Through getbalance() and setbalance(), the data must be provided Both are interface for outside person, hiding data behind methods Advantages Security Enhancement Maintainability Modularity Disadvantages Increase the length of the code Slow down the execution Validation must be required- lengthy process Example: For transferring funds→ user name + Password + card no + OTP 2. Comparison with Function oriented programming Functional Programming Object Oriented Programming This programming paradigm emphasizes on the use of This programming paradigm is based on object functions where each function performs a specific oriented concept. Classes are used where task. instance of objects are created Fundamental elements used are variables and Fundamental elements used are objects and functions.The data in the functions are methods and the data used here are mutable data. immutable(cannot be changed after creation). Importance is given to data rather than Importance is not given to data but to functions. procedures. Prepared By: Dr. R. H. Aswathy, AP(Sl. G.) / CSE Department, KPRIET, Coimbatore. Page 6 U21CSG04 – [UNIT I – OBJECT ORIENTED PROGRAMMING AND JAVA Java Programming BASICS] Functional Programming Object Oriented Programming It follows declarative programming model. It follows imperative programming model. It uses recursion for iteration. It uses loops for iteration. It is parallel programming supported. It does not support parallel programming. The statements in this programming paradigm The statements in this programming paradigm does need to follow an order i.e., bottom up approach not need to follow a particular order while execution. while execution. Has three access specifiers namely, Public, Does not have any access specifier. Private and Protected. Provides an easy way to add new data and To add new data and functions is not so easy. functions. No data hiding is possible. Hence, Security is not Provides data hiding. Hence, secured programs possible. are possible. 3. Characteristics of Java a. Platform Independent Java is compiled, it is not compiled into platform specific machine, rather into platform- independent byte code. This byte code is distributed over the web and interpreted by the Virtual Machine (JVM) on whichever platform it is being run on. b. Simple Java is designed to be easy to learn. c. Secure Java enables to develop virus-free, tamper-free systems. Authentication techniques are based on public-key encryption. Prepared By: Dr. R. H. Aswathy, AP(Sl. G.) / CSE Department, KPRIET, Coimbatore. Page 7 U21CSG04 – [UNIT I – OBJECT ORIENTED PROGRAMMING AND JAVA Java Programming BASICS] d. Architecture-neutral Java compiler generates an architecture-neutral object file format, which makes the compiled code executable on many processors, with the presence of Java runtime system. e. Portable Being architecture-neutral and having no implementation dependent aspects of the specification makes Java portable. The compiler in Java is written in ANSI C with a clean portability boundary f. Robust Java makes an effort to eliminate error-prone situations by emphasizing mainly on compile time error checking and runtime checking. g. Multithreaded Possible to write programs that can perform many tasks simultaneously. This design feature allows the developers to construct interactive applications that can run smoothly. h. Interpreted Java byte code is translated on the fly to native machine instructions and is not stored anywhere. The development process is more rapid and analytical since the linking is an incremental and light-weight process. i. High Performance With the use of Just-In-Time compilers, Java enables high performance. j. Distributed Java is designed for the distributed environment of the internet. k. Dynamic Java is considered to be more dynamic than C or C++ since it is designed to adapt to an evolving environment. Java programs can carry an extensive amount of run-time information that can be used to verify and resolve accesses to objects at run-time. JAVA Environment –JVM and JDK JVM JVM (Java Virtual Machine) is an abstract machine. It is called a virtual machine because it doesn't physically exist. It is a specification that provides a runtime environment in which Java bytecode can Prepared By: Dr. R. H. Aswathy, AP(Sl. G.) / CSE Department, KPRIET, Coimbatore. Page 8 U21CSG04 – [UNIT I – OBJECT ORIENTED PROGRAMMING AND JAVA Java Programming BASICS] be executed. It can also run those programs which are written in other languages and compiled to Java bytecode. JVMs are available for many hardware and software platforms. JVM, JRE, and JDK are platform dependent because the configuration of each OS is different from each other. However, Java is platform independent. There are three notions of the JVM: specification, implementation, and instance. The JVM performs the following main tasks: o Loads code o Verifies code o Executes code o Provides runtime environment More Details. JRE JRE is an acronym for Java Runtime Environment. It is also written as Java RTE. The Java Runtime Environment is a set of software tools which are used for developing Java applications. It is used to provide the runtime environment. It is the implementation of JVM. It physically exists. It contains a set of libraries + other files that JVM uses at runtime. The implementation of JVM is also actively released by other companies besides Sun Micro Systems. JDK JDK is an acronym for Java Development Kit. The Java Development Kit (JDK) is a software development environment which is used to develop Java applications and applets. It physically exists. It contains JRE + development tools. JDK is an implementation of any one of the below given Java Platforms released by Oracle Corporation: o Standard Edition Java Platform o Enterprise Edition Java Platform o Micro Edition Java Platform Prepared By: Dr. R. H. Aswathy, AP(Sl. G.) / CSE Department, KPRIET, Coimbatore. Page 9 U21CSG04 – [UNIT I – OBJECT ORIENTED PROGRAMMING AND JAVA Java Programming BASICS] The JDK contains a private Java Virtual Machine (JVM) and a few other resources such as an interpreter/loader (java), a compiler (javac), an archiver (jar), a documentation generator (Javadoc), etc. to complete the development of a Java Application. Fundamental programming Structure of Java Java is an object-oriented programming, platform-independent, and secure programming language that makes it popular. Prepared By: Dr. R. H. Aswathy, AP(Sl. G.) / CSE Department, KPRIET, Coimbatore. Page 10 U21CSG04 – [UNIT I – OBJECT ORIENTED PROGRAMMING AND JAVA Java Programming BASICS] Documentation Section The documentation section is an important section but optional for a Java program. Prepared By: Dr. R. H. Aswathy, AP(Sl. G.) / CSE Department, KPRIET, Coimbatore. Page 11 U21CSG04 – [UNIT I – OBJECT ORIENTED PROGRAMMING AND JAVA Java Programming BASICS] It includes basic information about a Java program. The information includes the author's name, date of creation, version, program name, company name, and description of the program. It improves the readability of the program. Whatever we write in the documentation section, the Java compiler ignores the statements during the execution of the program. To write the statements in the documentation section, we use comments. The comments may be single-line, multi-line, and documentation comments. Single-line Comment: It starts with a pair of forwarding slash (//). For example: //First Java Program Multi-line Comment: It starts with a. We write between these two symbols. For example: Documentation Comment: It starts with the delimiter (. For example: Package Declaration The package declaration is optional. It is placed just after the documentation section. There can be only one package statement in a Java program. It must be defined before any class and interface declaration. It is necessary because a Java class can be placed in different packages and directories based on the module they are used. Classes package belongs to a single parent directory. The keyword package to declare the package name. For example: package javatpoint; //where javatpoint is the package name package com.javatpoint; //where com is the root directory and javatpoint is the subdirectory Import Statements The package contains the many predefined classes and interfaces. Use any class of a particular package, we need to import that class. The import statement represents the class stored in the other package. import keyword to import the class. It is written before the class declaration and after the package statement. Prepared By: Dr. R. H. Aswathy, AP(Sl. G.) / CSE Department, KPRIET, Coimbatore. Page 12 U21CSG04 – [UNIT I – OBJECT ORIENTED PROGRAMMING AND JAVA Java Programming BASICS] import statement in two ways, either import a specific class or import all classes of a particular package. In a Java program, we can use multiple import statements. For example: import java.util.Scanner; //it imports the Scanner class only import java.util.*; //it imports all the class of the java.util package Interface Section It is an optional section. An interface in this section if required. interface keyword to create an interface. An interface is a slightly different from the class. It contains only constants and method declarations. Another difference is that it cannot be instantiated. interface in classes by using the implements keyword. An interface can also be used with other interfaces by using the extends keyword. For example interface car { void start(); void stop(); } Class Definition In this section, we define the class. It is vital part of a Java program. Without the class, we cannot create any Java program. A Java program may conation more than one class definition. The class keyword to define the class. The class is a blueprint of a Java program. It contains information about user-defined methods, variables, and constants. Every Java program has at least one class that contains the main() method. For example: class Student //class definition { } Class Variables and Constants Define variables and constants that are to be used later in the program. Java program, the variables and constants are defined just after the class definition. The variables and constants store values of the parameters. Prepared By: Dr. R. H. Aswathy, AP(Sl. G.) / CSE Department, KPRIET, Coimbatore. Page 13 U21CSG04 – [UNIT I – OBJECT ORIENTED PROGRAMMING AND JAVA Java Programming BASICS] It is used during the execution of the program. Decide and define the scope of variables by using the modifiers. It defines the life of the variables. For example: class Student //class definition { String sname; //variable int id; double percentage; } Main Method Class The main() method is essential for all Java programs. The execution of all Java programs starts from the main() method. It is an entry point of the class. It must be inside the class. The main method, we create objects and call the methods. The following statement to define the main() method: public static void main(String args[]) { } For example: public class Student //class definition { public static void main(String args[]) { //statements } } Methods and behavior The functionality of the program by using the methods. The methods are the set of instructions that we want to perform. These instructions execute at runtime and perform the specified task. For example: public class Demo //class definition { public static void main(String args[]) { void display() { Prepared By: Dr. R. H. Aswathy, AP(Sl. G.) / CSE Department, KPRIET, Coimbatore. Page 14 U21CSG04 – [UNIT I – OBJECT ORIENTED PROGRAMMING AND JAVA Java Programming BASICS] System.out.println("Welcome to javatpoint"); } //statements } } CheckPalindromeNumber.java //Author's name: Mathew //imports the Scanner class of the java.util package import java.util.Scanner; //class definition public class CheckPalindromeNumber { //main method public static void main(String args[]) { //variables to be used in program int r, s=0, temp; int x; //It is the number variable to be checked for palindrome Scanner sc=new Scanner(System.in); System.out.println("Enter the number to check: "); //reading a number from the user x=sc.nextInt(); //logic to check if the number id palindrome or not temp=x; while(x>0) { r=x%10; //finds remainder s=(s*10)+r; x=x/10; } if(temp==s) System.out.println("The given number is palindrome."); else System.out.println("The given number is not palindrome."); } Prepared By: Dr. R. H. Aswathy, AP(Sl. G.) / CSE Department, KPRIET, Coimbatore. Page 15 U21CSG04 – [UNIT I – OBJECT ORIENTED PROGRAMMING AND JAVA Java Programming BASICS] } OUTPUT Constructors in Java In Java, a constructor is a block of codes similar to the method. It is called when an instance of the class is created. At the time of calling constructor, memory for the object is allocated in the memory. It is a special type of method which is used to initialize the object. Every time an object is created using the new() keyword, at least one constructor is called. It calls a default constructor if there is no constructor available in the class. In such case, Java compiler provides a default constructor by default. Rules for creating Java constructor There are two rules defined for the constructor. 1. Constructor name must be the same as its class name 2. A Constructor must have no explicit return type 3. A Java constructor cannot be abstract, static, final, and synchronized Types of Java constructors There are two types of constructors in Java: 1. Default constructor (no-arg constructor) 2. Parameterized constructor 1. Java Default Constructor A constructor is called "Default Constructor" when it doesn't have any parameter. Syntax of default constructor: (){} Example of default constructor Prepared By: Dr. R. H. Aswathy, AP(Sl. G.) / CSE Department, KPRIET, Coimbatore. Page 16 U21CSG04 – [UNIT I – OBJECT ORIENTED PROGRAMMING AND JAVA Java Programming BASICS] In this example, we are creating the no-arg constructor in the Bike class. It will be invoked at the time of obje creation. //Java Program to create and call a default constructor class Bike1{ //creating a default constructor Bike1() { System.out.println("Bike is created"); } //main method public static void main(String args[]) { //calling a default constructor Bike1 b=new Bike1(); } } Q) What is the purpose of a default constructor? The default constructor is used to provide the default values to the object like 0, null, etc., depending on the type. Example of default constructor that displays the default values //Let us see another example of default constructor //which displays the default values class Student3 { int id; String name; Prepared By: Dr. R. H. Aswathy, AP(Sl. G.) / CSE Department, KPRIET, Coimbatore. Page 17 U21CSG04 – [UNIT I – OBJECT ORIENTED PROGRAMMING AND JAVA Java Programming BASICS] //method to display the value of id and name void display(){System.out.println(id+" "+name); } public static void main(String args[]) { //creating objects Student3 s1=new Student3(); Student3 s2=new Student3(); //displaying values of the object s1.display(); s2.display(); } } Output 0 null 0 null Explanation:In the above class,you are not creating any constructor so compiler provides you a default constructor. Here 0 and null values are provided by default constructor. 2. Java Parameterized Constructor A constructor which has a specific number of parameters is called a parameterized constructor. Why use the parameterized constructor? The parameterized constructor is used to provide different values to distinct objects. However, you can provide the same values also. Example of parameterized constructor In this example, we have created the constructor of Student class that have two parameters. We can have any number of parameters in the constructor. /Java Program to demonstrate the use of the parameterized constructor. class Student4{ int id; String name; //creating a parameterized constructor Student4(int i,String n){ Prepared By: Dr. R. H. Aswathy, AP(Sl. G.) / CSE Department, KPRIET, Coimbatore. Page 18 U21CSG04 – [UNIT I – OBJECT ORIENTED PROGRAMMING AND JAVA Java Programming BASICS] id = i; name = n; } //method to display the values void display(){System.out.println(id+" "+name);} public static void main(String args[]){ //creating objects and passing values Student4 s1 = new Student4(111,"Karan"); Student4 s2 = new Student4(222,"Aryan"); //calling method to display the values of object s1.display(); s2.display(); } } OUTPUT 111 karan 222 Aryan 7. Method in Java A method is a way to perform some task. Similarly, the method in Java is a collection of instructions that performs a specific task. It provides the reusability of code. Method in Java A method is a block of code or collection of statements or a set of code grouped together to perform a certain task or operation. It is used to achieve the reusability of code. We write a method once and use it many times. Do not require to write code again and again. It also provides the easy modification and readability of code, just by adding or removing a chunk of code. The method is executed only when we call or invoke it. The most important method in Java is the main() method. If you want to read more about the main() method, go through the link https://www.javatpoint.com/java-main-method Prepared By: Dr. R. H. Aswathy, AP(Sl. G.) / CSE Department, KPRIET, Coimbatore. Page 19 U21CSG04 – [UNIT I – OBJECT ORIENTED PROGRAMMING AND JAVA Java Programming BASICS] Method Declaration The method declaration provides information about method attributes, such as visibility, return- type, name, and arguments. It has six components that are known as method header Method Signature Every method has a method signature. It is a part of the method declaration. It includes the method name and parameter list. Return Type: Return type is a data type that the method returns. It may have a primitive data type, object, collection, void, etc. If the method does not return anything, we use void keyword. Method Name: It is a unique name that is used to define the name of a method. It must be corresponding to the functionality of the method. Creating a method for subtraction of two numbers, the method name must be subtraction(). A method is invoked by its name. Parameter List: It is the list of parameters separated by a comma and enclosed in the pair of parentheses. It contains the data type and variable name. Prepared By: Dr. R. H. Aswathy, AP(Sl. G.) / CSE Department, KPRIET, Coimbatore. Page 20 U21CSG04 – [UNIT I – OBJECT ORIENTED PROGRAMMING AND JAVA Java Programming BASICS] If the method has no parameter, left the parentheses blank. Method Body: It is a part of the method declaration. It contains all the actions to be performed. It is enclosed within the pair of curly braces. Naming a Method While defining a method, remember that the method name must be a verb and start with a lowercase letter. If the method name has more than two words, the first name must be a verb followed by adjective or noun. In the multi-word method name, the first letter of each word must be in uppercase except the first word. For example: Single-word method name: sum(), area() 1. Predefined Method Predefined methods are the method that is already defined in the Java class libraries is known as predefined methods. It is also known as the standard library method or built-in method. Directly use these methods just by calling them in the program at any point. Pre-defined methods are length(), equals(), compareTo(), sqrt(), etc. When we call any of the predefined methods in our program, a series of codes related to the corresponding method runs in the background that is already stored in the library. Each and every predefined method is defined inside a class. Such as o print() method is defined in the java.io.PrintStream class. It prints the statement that we write inside the method. For example, print("Java"), it prints Java on the console. Demo.java public class Demo { public static void main(String[] args) { // using the max() method of Math class Prepared By: Dr. R. H. Aswathy, AP(Sl. G.) / CSE Department, KPRIET, Coimbatore. Page 21 U21CSG04 – [UNIT I – OBJECT ORIENTED PROGRAMMING AND JAVA Java Programming BASICS] System.out.print("The maximum number is: " + Math.max(9,7)); } } Output: The maximum number is: 9 2. User-defined Method The method written by the user or programmer is known as a user-defined method. These methods are modified according to the requirement. How to Create a User-defined Method User defined method that checks the number is even or odd. First,define the method. //user defined method public static void findEvenOdd(int num) { //method body if(num%2==0) System.out.println(num+" is even"); else System.out.println(num+" is odd"); } We have defined the above method named findevenodd(). It has a parameter num of type int. The method does not return any value that's why we have used void. The method body contains the steps to check the number is even or odd. If the number is even, it prints the number is even, else prints the number is odd. How to Call or Invoke a User-defined Method The calling of a method in a program is simple. When we call or invoke a user-defined method, the program control transfer to the called method. import java.util.Scanner; public class EvenOdd { public static void main (String args[]) { Prepared By: Dr. R. H. Aswathy, AP(Sl. G.) / CSE Department, KPRIET, Coimbatore. Page 22 U21CSG04 – [UNIT I – OBJECT ORIENTED PROGRAMMING AND JAVA Java Programming BASICS] //creating Scanner class object Scanner scan=new Scanner(System.in); System.out.print("Enter the number: "); //reading value from the user int num=scan.nextInt(); //method calling findEvenOdd(num); } In the above code snippet, as soon as the compiler reaches at line findEvenOdd(num), the control transfer to the method and gives the output accordingly. Let's combine both snippets of codes in a single program and execute it. EvenOdd.java import java.util.Scanner; public class EvenOdd { public static void main (String args[]) { //creating Scanner class object Scanner scan=new Scanner(System.in); System.out.print("Enter the number: "); //reading value from user int num=scan.nextInt(); //method calling findEvenOdd(num); } //user defined method public static void findEvenOdd(int num) { //method body if(num%2==0) System.out.println(num+" is even"); else System.out.println(num+" is odd"); } } Output 1: Enter the number: 12 Prepared By: Dr. R. H. Aswathy, AP(Sl. G.) / CSE Department, KPRIET, Coimbatore. Page 23 U21CSG04 – [UNIT I – OBJECT ORIENTED PROGRAMMING AND JAVA Java Programming BASICS] 12 is even Output 2: Enter the number: 99 99 is odd 9. Static members Static members are those which belongs to the class and you can access these members without instantiating the class. The static keyword can be used with methods, fields, classes (inner/nested), and blocks. Static Methods Create a static method by using the keyword static. Static methods can access only static fields, methods. To access static methods there is no need to instantiate the class, you can do it just using the class name as − Example public class MyClass { public static void sample(){ System.out.println("Hello"); } public static void main(String args[]){ MyClass.sample(); } } Output : Hello Static Fields Create a static field by using the keyword static. The static fields have the same value in all the instances of the class. These are created and initialized when the class is loaded for the first time. Just like static methods you can access static fields using the class name (without instantiation). Example public class MyClass { public static int data = 20; public static void main(String args[]){ Prepared By: Dr. R. H. Aswathy, AP(Sl. G.) / CSE Department, KPRIET, Coimbatore. Page 24 U21CSG04 – [UNIT I – OBJECT ORIENTED PROGRAMMING AND JAVA Java Programming BASICS] System.out.println(MyClass.data); } Java Arrays with Answers 27 } Output: 20 Static Blocks These are a block of codes with a static keyword. These are used to initialize the static members. JVM executes static blocks before the main method at the time of class loading. Example public class MyClass { static{ System.out.println("Hello this is a static block"); } public static void main(String args[]){ System.out.println("This is main method"); } } Output Hello this is a static block This is main method Data types specify the different sizes and values that can be stored in the variable. There are two types of data types in Java: 1. Primitive data types: The primitive data types include boolean, char, byte, short, int, long, float and double. Prepared By: Dr. R. H. Aswathy, AP(Sl. G.) / CSE Department, KPRIET, Coimbatore. Page 25 U21CSG04 – [UNIT I – OBJECT ORIENTED PROGRAMMING AND JAVA Java Programming BASICS] 2. Non-primitive data types: The non-primitive data types include Classes, Interfaces, and Arrays. 1.Primitive Data Types In Java language, primitive data types are the building blocks of data manipulation. These are the most basic data types available in Java language. 8 Primitive Data Types There are 8 types of primitive data types: boolean data type byte data type char data type short data type int data type long data type float data type double data type 1. Boolean type The boolean data type has two possible values, either true or false. Default value: false. They are usually used for true/false conditions. Prepared By: Dr. R. H. Aswathy, AP(Sl. G.) / CSE Department, KPRIET, Coimbatore. Page 26 U21CSG04 – [UNIT I – OBJECT ORIENTED PROGRAMMING AND JAVA Java Programming BASICS] Example 1: Java boolean data type class Main { public static void main(String[] args) { boolean flag = true; System.out.println(flag); // prints true } } 2. Byte type The byte data type can have values from -128 to 127 (8-bit signed two's complement integer). If it's certain that the value of a variable will be within -128 to 127, then it is used instead of int to save memory. Default value: 0 Example 2: Java byte data type class Main { public static void main(String[] args) { byte range; range = 124; System.out.println(range); // prints 124 } } 3. Short type The short data type in Java can have values from -32768 to 32767 (16-bit signed two's complement integer). The value of a variable will be within -32768 and 32767, then it is used instead of other integer data types (int, long). Default value: 0 Example 3: Java short data type class Main { Prepared By: Dr. R. H. Aswathy, AP(Sl. G.) / CSE Department, KPRIET, Coimbatore. Page 27 U21CSG04 – [UNIT I – OBJECT ORIENTED PROGRAMMING AND JAVA Java Programming BASICS] public static void main(String[] args) { short temperature; temperature = -200; System.out.println(temperature); // prints -200 } } 4. Int type The int data type can have values from -231 to 231-1 (32-bit signed two's complement integer). If you are using Java 8 or later, you can use an unsigned 32-bit integer. This will have a minimum value of 0 and a maximum value of 232-1. Default value: 0 Example 4: Java int data type class Main { public static void main(String[] args) { int range = -4250000; System.out.println(range); // print -4250000 } } 5. Long type The long data type can have values from -263 to 263-1 (64-bit signed two's complement integer). If you are using Java 8 or later, you can use an unsigned 64-bit integer with a minimum value of 0 and a maximum value of 264-1. Default value: 0 Example 5: Java long data type class LongExample { public static void main(String[] args) { long range = -42332200000L; System.out.println(range); // prints -42332200000 Prepared By: Dr. R. H. Aswathy, AP(Sl. G.) / CSE Department, KPRIET, Coimbatore. Page 28 U21CSG04 – [UNIT I – OBJECT ORIENTED PROGRAMMING AND JAVA Java Programming BASICS] } } Note: The use of L at the end of -42332200000. This represents that it's an integer of the long type. 6. Double type The double data type is a double-precision 64-bit floating-point. It should never be used for precise values such as currency. Default value: 0.0 (0.0d) Example 6: Java double data type class Main { public static void main(String[] args) { double number = -42.3; System.out.println(number); // prints -42.3 } } 7. Float type The float data type is a single-precision 32-bit floating-point. Learn more about single-precision and double-precision floating-point if you are interested. It should never be used for precise values such as currency. Default value: 0.0 (0.0f) Example 7: Java float data type Note: class Main { we have used -42.3f instead of -42.3in the above program. It's because -42.3 is a double public static void main(String[] args) { literal. To tell the compiler to treat -42.3 as float rather float number = -42.3f; than double, you need to use f or F. System.out.println(number); // prints -42.3 } } 8. Char type It's a 16-bit Unicode character. Prepared By: Dr. R. H. Aswathy, AP(Sl. G.) / CSE Department, KPRIET, Coimbatore. Page 29 U21CSG04 – [UNIT I – OBJECT ORIENTED PROGRAMMING AND JAVA Java Programming BASICS] The minimum value of the char data type is '\u0000' (0) and the maximum value of the is '\uffff'. Default value: '\u0000' Example 8: Java char data type class Main { public static void main(String[] args) { char letter = '\u0051'; System.out.println(letter); // prints Q } 2. Types of Non-primitive Data types There are five types of non-primitive data types in Java. They are as follows: Class Object String Array Interface 1. Class and objects: Every class is data type and it is also considered as user-defined data types. This is because a user creates a class. For more details: Class and objects in java 2. String: A string represents a sequence of characters like India, ABC123, etc. The simplest way to create a string object is by storing sequence of characters into string type variable like this: String str = “Universe”; Here, string type variable str contains “Universe”. A string is also a class. For more details: String in Java. 3. Array: An array in java is an object which is used to store multiple variables of the same type. These variables can be primitive or non-primitive data types. The example of declaring an array variable of primitive data type int is as follows: int [ ] scores; The example of declaring an array variable of non-primitive data type is Prepared By: Dr. R. H. Aswathy, AP(Sl. G.) / CSE Department, KPRIET, Coimbatore. Page 30 U21CSG04 – [UNIT I – OBJECT ORIENTED PROGRAMMING AND JAVA Java Programming BASICS] Student [ ] students; // Student is a name of class. 4. Interface: An interface is declared like a class but the only difference is that it contains only final variables and method declarations. It is a fully abstract class. Difference between Primitive and Non-primitive Data types in Java 1. Primitive data types are predefined in Java whereas non-primitive data types are created by programmers. They are not predefined in Java. 2. In primitive data type, variables can store only one value at a time whereas, in non-primitive data type, we can store multiple values either the same type or different type or both. 3. All the data for primitive type variables are stored on the stack whereas, for reference types, the stack holds a pointer to the object on the heap. 11. Variable A variable is the name of a reserved area allocated in memory. It is a name of the memory location. It is a combination of "vary + able" which means its value can be changed. int data=50;//Here data is variable Types of Variables There are three types of variables in Java: local variable instance variable static variable 1) Local Variable A variable declared inside the body of the method is called local variable. Use this variable only within that method and the other methods in the class aren't even aware that the variable exists. A local variable cannot be defined with "static" keyword. 2) Instance Variable A variable declared inside the class but outside the body of the method, is called an instance variable. It is not declared as static. Prepared By: Dr. R. H. Aswathy, AP(Sl. G.) / CSE Department, KPRIET, Coimbatore. Page 31 U21CSG04 – [UNIT I – OBJECT ORIENTED PROGRAMMING AND JAVA Java Programming BASICS] It is called an instance variable because its value is instance-specific and is not shared among instances. 3) Static variable A variable that is declared as static is called a static variable. It cannot be local. Create a single copy of the static variable and share it among all the instances of the class. Memory allocation for static variables happens only once when the class is loaded in the memory. Example to understand the types of variables in java public class A { static int m=100;//static variable void method() { int n=90;//local variable } public static void main(String args[]) { int data=50;//instance variable } }//end of class Java Variable Example: Add Two Numbers public class Simple{ public static void main(String[] args){ int a=10; int b=10; int c=a+b; System.out.println(c); } } Output: 20 Java Variable Example: Widening Prepared By: Dr. R. H. Aswathy, AP(Sl. G.) / CSE Department, KPRIET, Coimbatore. Page 32 U21CSG04 – [UNIT I – OBJECT ORIENTED PROGRAMMING AND JAVA Java Programming BASICS] public class Simple{ public static void main(String[] args){ int a=10; float f=a; System.out.println(a); System.out.println(f); }} Output: 10 10.0 Java Variable Example: Narrowing (Typecasting) public class Simple{ public static void main(String[] args){ float f=10.5f; //int a=f;//Compile time error int a=(int)f; System.out.println(f); System.out.println(a); }} Output: 10.5 10 12. Operators in Java Operator in Java is a symbol that is used to perform operations. For example: +, -, *, / etc. There are many types of operators in Java which are given below: Arithmetic Operator Assignment Operator Relational Operator Logical Operator Unary Operator Prepared By: Dr. R. H. Aswathy, AP(Sl. G.) / CSE Department, KPRIET, Coimbatore. Page 33 U21CSG04 – [UNIT I – OBJECT ORIENTED PROGRAMMING AND JAVA Java Programming BASICS] Bitwise Operator Ternary Operator 1) Java Arithmetic Operators Arithmetic operators are used to perform arithmetic operations on variables and data. Operator Operation + Addition - Subtraction * Multiplication / Division % Modulo Operation (Remainder after division) Example : Arithmetic Operators class Main { public static void main(String[] args) { // declare variables Output int a = 12, b = 5; a + b = 17 // addition operator a-b=7 System.out.println("a + b = " + (a + b)); a * b = 60 // subtraction operator a/b=2 a%b=2 System.out.println("a - b = " + (a - b)); // multiplication operator System.out.println("a * b = " + (a * b)); // division operator System.out.println("a / b = " + (a / b)); // modulo operator System.out.println("a % b = " + (a % b)); }} 2. Java Assignment Operators Assignment operators are used in Java to assign values to variables. For example, int age; age = 5; Prepared By: Dr. R. H. Aswathy, AP(Sl. G.) / CSE Department, KPRIET, Coimbatore. Page 34 U21CSG04 – [UNIT I – OBJECT ORIENTED PROGRAMMING AND JAVA Java Programming BASICS] Here, = is the assignment operator. It assigns the value on its right to the variable on its left. That is, 5 is assigned to the variable age. Operator Example Equivalent to = a = b; a = b; += a += b; a = a + b; -= a -= b; a = a - b; *= a *= b; a = a * b; /= a /= b; a = a / b; %= a %= b; a = a % b; Example 2: Assignment Operators class Main { public static void main(String[] args) { // create variables int a = 4; Output int var; // assign value using = a + b = 17 a-b=7 var = a; a * b = 60 System.out.println("var using =: " + var); a/b=2 // assign value using =+ a%b=2 var += a; System.out.println("var using +=: " + var); // assign value using =* var *= a; System.out.println("var using *=: " + var); }} Output var using =: 4 var using +=: 8 var using *=: 32 Prepared By: Dr. R. H. Aswathy, AP(Sl. G.) / CSE Department, KPRIET, Coimbatore. Page 35 U21CSG04 – [UNIT I – OBJECT ORIENTED PROGRAMMING AND JAVA Java Programming BASICS] 3. Java Relational Operators Relational operators are used to check the relationship between two operands. For example, // check if a is less than b a < b; Here, < operator is the relational operator. It checks if a is less than b or not. It returns either true or false. Operator Description Example == Is Equal To 3 == 5 returns false != Not Equal To 3 != 5 returns true > Greater Than 3 > 5 returns false < Less Than 3 < 5 returns true >= Greater Than or Equal To 3 >= 5 returns false b); // false // < operator System.out.println(a < b); // true // >= operator Prepared By: Dr. R. H. Aswathy, AP(Sl. G.) / CSE Department, KPRIET, Coimbatore. Page 36 U21CSG04 – [UNIT I – OBJECT ORIENTED PROGRAMMING AND JAVA Java Programming BASICS] System.out.println(a >= b); // false // 5)); // true System.out.println((5 > 3) && (8 < 5)); // false // || operator System.out.println((5 < 3) || (8 > 5)); // true System.out.println((5 > 3) || (8 < 5)); // true System.out.println((5 < 3) || (8 < 5)); // false // ! operator System.out.println(!(5 == 3)); // true System.out.println(!(5 > 3)); // false } } Prepared By: Dr. R. H. Aswathy, AP(Sl. G.) / CSE Department, KPRIET, Coimbatore. Page 37 U21CSG04 – [UNIT I – OBJECT ORIENTED PROGRAMMING AND JAVA Java Programming BASICS] Working of Program (5 > 3) && (8 > 5) returns true because both (5 > 3) and (8 > 5) are true. (5 > 3) && (8 < 5) returns false because the expression (8 < 5) is false. (5 < 3) || (8 > 5) returns true because the expression (8 > 5) is true. (5 > 3) && (8 > 5) returns true because the expression (5 > 3) is true. (5 > 3) && (8 > 5) returns false because both (5 < 3) and (8 < 5) are false. !(5 == 3) returns true because 5 == 3 is false. !(5 > 3) returns false because 5 > 3 is true. 5. Java Unary Operators Unary operators are used with only one operand. For example, ++ is a unary operator that increases the value of a variable by 1. That is, ++5 will return 6. Different types of unary operators are: Operator Meaning + Unary plus: not necessary to use since numbers are positive without using it - Unary minus: inverts the sign of an expression ++ Increment operator: increments value by 1 -- Decrement operator: decrements value by 1 ! Logical complement operator: inverts the value of a boolean Increment and Decrement Operators Java also provides increment and decrement operators: ++ and -- respectively. ++ increases the value of the operand by 1, while -- decrease it by 1. For example, int num = 5; // increase num by 1 ++num; The value of num gets increased to 6 from its initial value of 5. Example 5: Increment and Decrement Operators class Main { Prepared By: Dr. R. H. Aswathy, AP(Sl. G.) / CSE Department, KPRIET, Coimbatore. Page 38 U21CSG04 – [UNIT I – OBJECT ORIENTED PROGRAMMING AND JAVA Java Programming BASICS] public static void main(String[] args) { // declare variables int a = 12, b = 12; int result1, result2; // original value System.out.println("Value of a: " + a); // increment operator result1 = ++a; System.out.println("After increment: " + result1); System.out.println("Value of b: " + b); // decrement operator result2 = --b; System.out.println("After decrement: " + result2); }} Output Value of a: 12 After increment: 13 Value of b: 12 After decrement: 11 In the above program, we have used the ++ and -- operator as prefixes (++a, --b). We can also use these operators as postfix (a++, b++). 6. Java Bitwise Operators Bitwise operators in Java are used to perform operations on individual bits. For example, Bitwise complement Operation of 35 35 = 00100011 (In Binary) ~ 00100011 ________ 11011100 = 220 (In decimal) Here, ~ is a bitwise operator. It inverts the value of each bit (0 to 1 and 1 to 0). The various bitwise operators present in Java are: Prepared By: Dr. R. H. Aswathy, AP(Sl. G.) / CSE Department, KPRIET, Coimbatore. Page 39 U21CSG04 – [UNIT I – OBJECT ORIENTED PROGRAMMING AND JAVA Java Programming BASICS] Operator Description ~ Bitwise Complement > Right Shift >>> Unsigned Right Shift & Bitwise AND ^ Bitwise exclusive OR These operators are not generally used in Java. To learn more, visit Java Bitwise and Bit Shift Operators. Other operators Besides these operators, there are other additional operators in Java. Java instanceof Operator The instanceof operator checks whether an object is an instanceof a particular class. For example, class Main { public static void main(String[] args) { String str = "Programiz"; boolean result; // checks if str is an instance of // the String class result = str instanceof String; System.out.println("Is str an object of String? " + result); } } Output Is str an object of String? true Here, str is an instance of the String class. Hence, the instanceof operator returns true. Prepared By: Dr. R. H. Aswathy, AP(Sl. G.) / CSE Department, KPRIET, Coimbatore. Page 40 U21CSG04 – [UNIT I – OBJECT ORIENTED PROGRAMMING AND JAVA Java Programming BASICS] 7. Java Ternary Operator The ternary operator (conditional operator) is shorthand for the if-then-else statement. For example, variable = Expression ? expression1 : expression2 If the Expression is true, expression1 is assigned to the variable. If the Expression is false, expression2 is assigned to the variable. Let's see an example of a ternary operator. class Java { public static void main(String[] args) { int februaryDays = 29; String result; // ternary operator result = (februaryDays == 28) ? "Not a leap year" : "Leap year"; System.out.println(result); } } Output Leap year In the above example, we have used the ternary operator to check if the year is a leap year or not. To learn more, visit the Java ternary operator. 13. Control Flow in Java Java compiler executes the code from top to bottom. The statements in the code are executed according to the order in which they appear. Java provides statements that can be used to control the flow of Java code. Java provides three types of control flow statements. 1. Decision Making statements o if statements o switch statement Prepared By: Dr. R. H. Aswathy, AP(Sl. G.) / CSE Department, KPRIET, Coimbatore. Page 41 U21CSG04 – [UNIT I – OBJECT ORIENTED PROGRAMMING AND JAVA Java Programming BASICS] 2. Loop statements o do while loop o while loop o for loop o for-each loop 3. Jump statements o break statement o continue statement 1. Decision-Making statements: Decision-making statements decide which statement to execute and when. Decision-making statements evaluate the Boolean expression and control the program flow depending upon the result of the condition provided. There are two types of decision-making statements in Java If statement Switch statement. a) If Statement The "if" statement is used to evaluate a condition. The control of the program is diverted depending upon the specific condition. The condition of the If statement gives a Boolean value, either true or false. There are four types of if-statements given below. 1. Simple if statement 2. if-else statement 3. if-else-if ladder 4. Nested if-statement 1) Simple if statement: It evaluates a Boolean expression and enables the program to enter a block of code if the expression evaluates to true. Syntax of if statement is given below. if(condition) { statement 1; //executes when condition is true Prepared By: Dr. R. H. Aswathy, AP(Sl. G.) / CSE Department, KPRIET, Coimbatore. Page 42 U21CSG04 – [UNIT I – OBJECT ORIENTED PROGRAMMING AND JAVA Java Programming BASICS] } Consider the following example in which we have used the if statement in the java code. Student.java Student.java public class Student { public static void main(String[] args) { int x = 10; int y = 12; if(x+y > 20) { System.out.println("x + y is greater than 20"); } } } Output: x + y is greater than 20 2) if-else statement The if-else statement is an extension to the if-statement, which uses another block of code, i.e., else block. The else block is executed if the condition of the if-block is evaluated as false. Syntax: if(condition) { statement 1; //executes when condition is true } else{ statement 2; //executes when condition is false } Consider the following example. Student.java public class Student { public static void main(String[] args) { int x = 10; Prepared By: Dr. R. H. Aswathy, AP(Sl. G.) / CSE Department, KPRIET, Coimbatore. Page 43 U21CSG04 – [UNIT I – OBJECT ORIENTED PROGRAMMING AND JAVA Java Programming BASICS] int y = 12; if(x+y < 10) { System.out.println("x + y is less than 10"); } else { System.out.println("x + y is greater than 20"); } } } Output: x + y is greater than 20 3) if-else-if ladder: The if-else-if statement contains the if-statement followed by multiple else-if statements. The chain of if-else statements that create a decision tree where the program may enter in the block of code where the condition is true. Also,define an else statement at the end of the chain. Syntax of if-else-if statement is given below. if(condition 1) { statement 1; //executes when condition 1 is true } else if(condition 2) { statement 2; //executes when condition 2 is true } else { statement 2; //executes when all the conditions are false } Consider the following example. Student.java public class Student { public static void main(String[] args) { String city = "Delhi"; if(city == "Meerut") { System.out.println("city is meerut"); }else if (city == "Noida") { Prepared By: Dr. R. H. Aswathy, AP(Sl. G.) / CSE Department, KPRIET, Coimbatore. Page 44 U21CSG04 – [UNIT I – OBJECT ORIENTED PROGRAMMING AND JAVA Java Programming BASICS] System.out.println("city is noida"); }else if(city == "Agra") { System.out.println("city is agra"); }else { System.out.println(city); } } } Output: Delhi 4. Nested if-statement In nested if-statements, the if statement can contain a if or if-else statement inside another if or else-if statement. Syntax of Nested if-statement is given below. if(condition 1) { statement 1; //executes when condition 1 is true if(condition 2) { statement 2; //executes when condition 2 is true } else{ statement 2; //executes when condition 2 is false } } Student.java public class Student { public static void main(String[] args) { String address = "Delhi, India"; if(address.endsWith("India")) { if(address.contains("Meerut")) { System.out.println("Your city is Meerut"); }else if(address.contains("Noida")) { System.out.println("Your city is Noida"); }else { Prepared By: Dr. R. H. Aswathy, AP(Sl. G.) / CSE Department, KPRIET, Coimbatore. Page 45 U21CSG04 – [UNIT I – OBJECT ORIENTED PROGRAMMING AND JAVA Java Programming BASICS] System.out.println(address.split(",")); } }else { System.out.println("You are not living in India"); } } } Output: Delhi b)Switch Statement: Switch statements are similar to if-else-if statements. The switch statement contains multiple blocks of code called cases and a single case is executed based on the variable which is being switched. The switch statement is easier to use instead of if-else-if statements. It also enhances the readability of the program. Points to be noted about switch statement: The case variables can be int, short, byte, char, or enumeration. String type is also supported since version 7 of Java Cases cannot be duplicate Default statement is executed when any of the case doesn't match the value of expression. It is optional. Break statement terminates the switch block when the condition is satisfied. It is optional, if not used, next case is executed. While using switch statements, we must notice that the case expression will be of the same type as the variable. However, it will also be a constant value. The syntax to use the switch statement is given below. switch (expression){ case value1: statement1; break;... Prepared By: Dr. R. H. Aswathy, AP(Sl. G.) / CSE Department, KPRIET, Coimbatore. Page 46 U21CSG04 – [UNIT I – OBJECT ORIENTED PROGRAMMING AND JAVA Java Programming BASICS] case valueN: statementN; break; default: default statement; } Consider the following example to understand the flow of the switch statement. Student.java public class Student implements Cloneable { public static void main(String[] args) { int num = 2; switch (num){ case 0: System.out.println("number is 0"); break; case 1: System.out.println("number is 1"); break; default: System.out.println(num); } } } Output: 2 Example: Java Program to Make a Simple Calculator Using switch...case CODE: import java.util.Scanner; class Main { public static void main(String[] args) { char operator; Prepared By: Dr. R. H. Aswathy, AP(Sl. G.) / CSE Department, KPRIET, Coimbatore. Page 47 U21CSG04 – [UNIT I – OBJECT ORIENTED PROGRAMMING AND JAVA Java Programming BASICS] Double number1, number2, result; // create an object of Scanner class Scanner input = new Scanner(System.in); // ask users to enter operator System.out.println("Choose an operator: +, -, *, or /"); operator = input.next().charAt(0); // ask users to enter numbers System.out.println("Enter first number"); number1 = input.nextDouble(); System.out.println("Enter second number"); number2 = input.nextDouble(); switch (operator) { // performs addition between numbers case '+': result = number1 + number2; System.out.println(number1 + " + " + number2 + " = " + result); break; // performs subtraction between numbers case '-': result = number1 - number2; System.out.println(number1 + " - " + number2 + " = " + result); break; // performs multiplication between numbers case '*': result = number1 * number2; System.out.println(number1 + " * " + number2 + " = " + result); break; // performs division between numbers case '/': result = number1 / number2; System.out.println(number1 + " / " + number2 + " = " + result); break; Prepared By: Dr. R. H. Aswathy, AP(Sl. G.) / CSE Department, KPRIET, Coimbatore. Page 48 U21CSG04 – [UNIT I – OBJECT ORIENTED PROGRAMMING AND JAVA Java Programming BASICS] default: System.out.println("Invalid operator!"); break; } }} While using switch statements, we must notice that the case expression will be of the same type as the variable. It will also be a constant value. The switch permits only int, string, and Enum type variables to be used. b) Loop Statements To execute the block of code repeatedly while some condition evaluates to true. Loop statements are used to execute the set of instructions in a repeated order. The execution of the set of instructions depends upon a particular condition. Three types of loops that execute similarly. However, there are differences in their syntax and condition checking time. 1. for loop 2. while loop 3. do-while loop 1. for loop To check the condition, and increment/decrement in a single line of code. Use for loop only when we exactly know the number of times, we want to execute the block of code. for(initialization, condition, increment/decrement) { //block of statements } The flow chart for the for-loop is given below. Prepared By: Dr. R. H. Aswathy, AP(Sl. G.) / CSE Department, KPRIET, Coimbatore. Page 49 U21CSG04 – [UNIT I – OBJECT ORIENTED PROGRAMMING AND JAVA Java Programming BASICS] Consider the following example to understand the proper functioning of the for loop in java. Calculation.java public class Calculattion { public static void main(String[] args) { // TODO Auto-generated method stub int sum = 0; for(int j = 1; j