
























































Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
Community
Ask the community for help and clear up your study doubts
Discover the best universities in your country according to Docsity users
Free resources
Download our free guides on studying techniques, anxiety management strategies, and thesis advice from Docsity tutors
A comprehensive overview of fundamental java programming concepts, including control statements, classes, and objects. It covers essential elements like variables, data types, operators, and control flow mechanisms. The document also delves into object-oriented programming principles, explaining classes, objects, inheritance, polymorphism, and packages. It includes examples and code snippets to illustrate key concepts.
Typology: Study Guides, Projects, Research
1 / 64
This page cannot be seen from the preview
Don't miss anything!
Java is a general-purpose computer programming language that is concurrent, class-based, object-oriented, and specifically designed to have as few implementation dependencies as possible. It is intended to let application developers "write once, run anywhere" (WORA), meaning that compiled Java code can run on all platforms that support Java without the need for recompilation. For example, you can write and compile a Java program on UNIX and run it on Microsoft Windows, Macintosh, or UNIX machine without any modifications to the source code. WORA is achieved by compiling a Java program into an intermediate language called byte code. The format of byte code is platform-independent. A virtual machine, called the Java Virtual Machine (JVM), is used to run the byte code on each platform.
Java was originally developed by James Gosling at Sun Microsystems (which has since been acquired by Oracle Corporation) and released in 1995 as a core component of Sun Microsystems' Java platform. The language derives much of its syntax from C and C++, but it has fewer low-level facilities than either of them. Oracle Corporation is the current owner of the official implementation of the Java SE platform, following their acquisition of Sun Microsystems on January 27, 2010. This implementation is based on the original implementation of Java by Sun. The Oracle implementation is available for Microsoft Windows, Mac OS X, Linux and Solaris. The Oracle implementation is packaged into two different distributions: Java Runtime Environment (JRE) which contains the parts of the Java SE platform required to run Java programs and is intended for end users, and Java Development Kit (JDK) which is intended for software developers and includes development tools such as the Java compiler, Javadoc, Jar, and a debugger.
Java program normally go through five phases:
Edit Compile Load Verify Execute
The programmer types a Java program using an editor like Notepad, and makes corrections if necessary. The Java program file name ends with a .java extension. In the Compile phase, the Java compiler translates the Java program into bytecodes, which is the language understood by the Java interpreter. In the Load phase, the program must first be placed in memory before it can be executed. This is done by the class loader, which takes the .class file (or files) containing the bytecodes and transfers it to memory. Before the bytecodes in an application are executed by the Java interpreter, they are verified by the bytecode verifier in the Verify phase. This ensures that the bytecodes for class that are loaded form the internet (referred to as downloaded classes) are valid and that they do not violate Java's security restrictions. Finally, in the Execute phase, the computer, under the control of its CPU, interprets the program one bytecode at a time, performing the actions specified by the program.
Distributed : Java supports Remote Method Invocation (RMI), which allows access of a method from anywhere over the network. Secure : Java is secure because it is using Applet. When Applet is running, it not allowing access to other parts of the computer. There is no pointer in Java, and it does not allow direct memory access that secures Java program from unauthorized access. Object-Oriented : Java is an object-oriented language. It consists of classes and objects. Java program starts from the class. It advocates that Java is an object-oriented language. Reliable : Java provides automatic memory management and exception handling features for producing reliable software. Interpreted : Java source file is compiled by Java compiler into bytecode, which is then interpreted by the Java Virtual Machine (JVM). Multithreaded : Java provides the facility of multithreading, which allows a program to be written with multiple threads running simultaneously. High Performance : Java bytecode can be easily translated directly into machine code by the JVM/JIT, giving high performance to Java code. Architecture-Neutral : Java's "Write once, run anywhere" goal is accomplished by the Java Virtual Machine (JVM). Dynamic : Java is able to access objects at run-time.
The Java Development Kit (JDK) is a software development environment used to develop Java applications and applets. It contains a private Java Virtual Machine (JVM) and various development tools such as the Java compiler, Javadoc, Jar, and a debugger. The JDK is an implementation of any one of the Java Platforms released by Oracle Corporation.
Some of the primary components of the JDK include:
appletviewer: Used to run and debug Java applets without a web browser.
Scope : The scope of a variable determines where it can be accessed within a program. Comments : Java supports single-line (//), multi-line (/* /), and Javadoc (/* */) comments. Keyboard Input : Java provides the Scanner class for reading input from the keyboard.
Java provides the following control statements:
Conditional Statements : if-else, switch-case Looping Statements : for, while, do-while Break and Continue Statements : break and continue statements can be used to control the flow of loops.
Java is an object-oriented programming language, and the fundamental building blocks are classes and objects. Key concepts related to classes and objects include:
Modifiers : Access modifiers (public, private, protected) and non- access modifiers (static, final, abstract) can be used to control the visibility and behavior of classes, methods, and variables. Arguments : Methods can accept arguments (parameters) to receive input data. Constructors : Constructors are special methods used to initialize the state of an object when it is created. Packages and import : Packages are used to organize related classes, and the import statement is used to access classes from other packages. Static Class : A static class is a nested class that can be accessed without creating an instance of the outer class. Overloaded Methods and Constructors : Java allows the definition of multiple methods or constructors with the same name but different parameters. Returning Objects : Methods can return objects as their output. toString() : The toString() method is used to provide a string representation of an object. this reference : The this keyword refers to the current object instance. Enumeration : Enumerations are a special data type that allows you to define a set of named constants. Garbage Collection : Java's automatic memory management system, known as garbage collection, reclaims the memory occupied by objects that are no longer in use.
Java OOP Features
It specifies the policy creation and management tool, which can determine policy for a Java runtime, specifying which permissions are available for code from various sources.
VisualVM is a visual tool integrating several command-line JDK tools and lightweight performance and memory profiling capabilities.
wsimport generates portable JAX-WS artifacts for invoking a web service. It is part of the Java API for XML Binding (JAXB) API. It accepts an XML schema and generates Java classes.
The main OOP concepts that one must learn to understand Object Oriented Programming in Java are:
Abstraction is a process where you show only "relevant" data and "hide" unnecessary details of an object from the user. For example, when you login to your bank account online, you enter your user_id and password and press login, what happens when you press login, how the input data is sent to the server, and how it gets verified is all abstracted away from the user.
Encapsulation simply means binding object state (fields) and behavior (methods) together. When creating a class, you are doing encapsulation. To achieve encapsulation:
Make the instance variables private so that they cannot be accessed directly from outside the class. You can only set and get values of these variables through the methods of the class. Have getter and setter methods in the class to set and get the values of the fields.
Example: ```java class EmployeeCount { private int numOfEmployees = 0;
public void setNoOfEmployees(int count) { numOfEmployees = count; }
concept of one class extending more than one classes, which means a child class has two parent classes. Java does not support multiple inheritance.
Polymorphism is an OOP feature that allows us to perform a single action in different ways. For example, we can have a class Animal with an abstract method animalSound(). Then, the classes Dog and Lion that extend Animal can provide their own implementation of the animalSound() method.
Types of Polymorphism: 1. Static Polymorphism : Polymorphism that is resolved during compile time, such as method overloading. Example: ```java class DisplayOverloading { public void disp(char c) { System.out.println(c); }
public void disp(char c, int num) { System.out.println(c + " " + num); }
}
public class ExampleOverloading { public static void main(String args[]) { DisplayOverloading obj = new DisplayOverloading(); obj.disp('a'); obj.disp('a', 10); } } ```
Dynamic Polymorphism : Also known as Dynamic Method Dispatch, this is a process in which a call to an overridden method is resolved at runtime. Example: ```java class Animal { public void animalSound() { System.out.println("Default Sound"); } }
public class Dog extends Animal { public void animalSound() { System.out.println("Woof"); }
public static void main(String args[]) { Animal obj = new Dog(); obj.animalSound(); }
} ```
IS-A Relationship : A Car IS-A Vehicle. HAS-A Relationship : A Car HAS-A License.
Example: ```java public class Vehicle {}
public class Car extends Vehicle { private License myCarLicense; } ```
Java variables are memory allocations where values are stored, which can later be manipulated by the program. Each variable has a specific type, which determines its memory and the data that can be stored in it.
Variable Declaration
There are three ways to declare variables: 1. Datatype: The datatype is the type of data in which the variable is stored. 2. Variable_name: The name of the variable. 3. Value: The initial value stored in the variable.
Example: java float simpleInterest; // Declaring a float variable int time = 10, speed = 20; // Declaring and initializing integer variables char var = 'h'; // Declaring and initializing a character variable
Types of Variables
Local Variables : Defined within a method, block, or constructor, and their scope is limited to the particular block. Instance Variables : Declared in a class, outside any method, constructor, or block. They are of the static type and are created when an object is created and destroyed when the object is destroyed. Static Variables : Declared using the static keyword, outside any object, block, or constructor. They can have multiple copies and are initialized at the beginning of program execution and destroyed when the program ends.
Literals are constant values assigned to variables. There are five types of literals in Java:
Integral Literals : Can be specified in decimal (base 10), octal (base 8), hexadecimal (base 16), or binary (base 2) form. Floating-Point Literals : Represent decimal numbers. Boolean Literals : Represent true or false. Character Literals : Represent single characters enclosed within single quotes. String Literals : Represent a sequence of characters enclosed within double quotes.
Integral Literals in Java
Example: java int decimalValue = 123; // decimal-form literal
A char literal in Java can be specified as an integral literal, which also represents the Unicode value of a character. Furthermore, an integer can be specified in decimal, octal, and even hexadecimal type, but the range is 0-65535. Example: char ch = 062;
Char literals can be specified in Unicode representation '\uxxxx', where xxxx represents 4 hexadecimal numbers. Example: char unicodeCharacter = '\u0064';
Escape sequences can also be specified as char literals. Example: char ch = '\n';
Example: java package com.dataflair.literals; public class CharacterLiteral { public static void main(String[] args) { char character = 'd'; char unicodeCharacter = '\u0064'; System.out.println(character); System.out.println(unicodeCharacter); System.out.println('' is a symbol'); } }
String Literals
Java string literals are any sequence of characters enclosed within double quotes. They may not contain unescaped newline or linefeed characters. However, the Java compiler will evaluate compile-time expressions.
Example: java package com.dataflair.literals; public class StringLiteral { public static void main(String[] args) { String myString = 'Hello! Welcome to DataFlair'; System.out.println(myString); } }
Boolean Literals
Boolean literals in Java allow only two values: true and false.
Example: java package com.dataflair.literals; public class BooleanLiteral { public static void main(String[] args) { boolean boolVar1 = true; boolean boolVar2 = false; System.out.println(boolVar1); System.out.println(boolVar2); } }
Java is a statically typed language, which means that every variable and keyword must be assigned a data type, and they are predefined.
There are two types of data types in Java:
Primitive Data Types Non-Primitive Data Types
Primitive Data Types in Java
Java has eight primitive data types:
Represents a single bit of information, either true or false. Example: java class boolean { public static void main(String args[]) { boolean b = true; if (b == true) System.out.println('true'); } }
A signed two's complement integer with a size of 8 bits and a range from -128 to 127. Example: java class byte { public static void main(String args[]) { byte a = 126; System.out.println(a); } }
A single 16-bit Unicode character with a range from '\u0000' (0) to '\uffff' (65535). Example: java class short { public static void main(String args[]) { char a = 'G'; System.out.println(a); } }
A signed two's complement integer with a size of 16 bits and a range from -32,768 to 32,767 (inclusive). Example: java class short { public static void main(String args[]) { short a = 56; System.out.println(a); } }
A signed two's complement integer with a size of 32 bits and a range from -2^31 to 2^31-1. Example: java class int { public static void main(String args[]) { int a = 56; System.out.println(a); } }
Example: ```java package JavaOperatorsDemo; public class UsingArithematicOperator { public static void main(String[] args) { int operand1 = 20, operand2 = 10; String stringname1 = 'DataFlair's', stringname2 = ' Java Tutorial';
// using + operator with strings it will concatenate the strings System.out.println('Welcome to '+stringname1 +stringname2);
// using + and - arithmetic operator System.out.println('Adding(+) two operands= '+(operand1 + operand2)); System.out.println('Subtracting(-) two operands= '+(operand1 - operand
// * and / operator System.out.println('Multiplying(*) two operands= '+(operand1 * operand System.out.println('Dividing(/) two operands= '+(operand1 / operand2))
// modulus operator gives remainder on dividing first operand with sec System.out.println('Modulus(%) of two operands= '+(operand1 % operand }
} ```
Unary Operators in Java
Unary operators operate on a single value.
The unary operators in Java are: - Unary Minus (-) - Unary Plus (+) - Increment Operator (++) - Decrement Operator (--) - Logical Not Operator (!)
Example: ```java package JavaOperatorsDemo; public class UsingUnaryOperator { public static void main(String[] args) { int operand = 20, operand2 = 10, operand3 = 0, operand4 = 20, operand5 = 40; boolean condition = true;
// pre-increment operator operand3 = ++operand1; // operand1 = operand1 + 1 System.out.println('Value of operand3 (++operand1) = ' + operand3); //
// post increment operator operand3 = operand2++; // operand3 = b System.out.println('Value of operand3 (operand2++) = ' + operand3); //
// pre-decrement operator operand3 = --operand4; // operand4 = operand4- System.out.println('Value of operand3 (--operand4) = ' + operand3); //
// post-decrement operator operand3 = --operand5; // operand3 = operand System.out.println('Value of operand3 (--operand5) = ' + operand3); //
// Logical not operator
System.out.println('Value of !condition =' + !condition); }
} ```
Assignment Operators in Java
Assignment operators assign a value to the left operand based on the value of the right operand using the = sign.
The assignment operators in Java are: - += - -= - *= - /= - ^= - %=
Example: ```java package JavaOperatorsDemo; public class UsingAssignmentOperator { public static void main(String[] args) { int operand1 = 20, operand2 = 10, operand3 = 10, operand4 = 4;
// simple assignment operator operand3 = operand2; System.out.println('Value of operand3 = ' + operand3);
// This following statement would throw an exception as value of right // before an assignment, and the program would not compile. // operand3 = operand4; }
} ```
Java Operators
java operand1 = operand1 + 1; operand2 = operand2 - 1; operand3 = operand3 * 2; operand4 = operand4 / 2; System.out.println('operand1,operand2,operand3,operand4 = ' + operand1 + ',' + operand2 + ',' + operand3 + ',' +operand4); operand1 = operand1 - 1; operand2 = operand2 + 1; operand3 = operand3 / 2; operand4 = operand4 * 2; // shorthand assignment operator operand1 += 1; operand2 -= 1; operand3 *= 2; operand4 /= 2; System.out.println('operand1,operand2,operand3,operand4 (using shorthand operators)= ' + operand1 + ',' + operand2 + ',' + operand3 + ',' + operand4);
The code demonstrates the use of various arithmetic operators in Java, including addition, subtraction, multiplication, and division. It also showcases the use of shorthand assignment operators, which provide a more concise way of performing arithmetic operations.
The code demonstrates the use of the logical AND operator to check if the user's input matches the expected values.
The ternary operator in Java is a shorthand version of an if-else statement. The syntax is as follows:
condition? value1 : value
If the condition is true, the value1 is executed, otherwise, value2 is executed.
java int operand1 = 20, operand2 = 10, operand3 = 30, result; // result holds max of three numbers result = ((operand1 > operand2) ? operand1 : operand3 : (operand2 > operand3)? operand2 : operand3);//using ternary operator System.out.println('Maximum out of three numbers = '+result);
The code uses the ternary operator to determine the maximum of three numbers.
Bitwise operators in Java perform operations on the individual bits of the operands. The following table outlines the various bitwise operators and their descriptions:
| Operator Name | Description | | --- | --- | | & (Bitwise AND) | The & operator compares corresponding bits of two operands. If both bits are 1, it gives 1 else 0. | | | (Bitwise OR) | The | operator compares corresponding bits of two operands. If either of the bits is 1, it gives 1 else 0. | | ^ (Bitwise XOR) | The ^ operator compares corresponding bits of two operands. If corresponding bits are different, it gives 1 else 0. | | ~ (Bitwise Complement) | The ~ operator inverts the bit pattern. It makes every 0 to 1 and every 1 to
// bitwise AND // 0101 & 0111 = 0101 System.out.println('operand1 & operand2 = ' + (operand1 & operand2)) ; // bitwise OR // 0101 | 0111=0111 System.out.println('operand1 | operand = ' + (operand1 | operand2)) ; // bitwise Complement // ~ 0101 = 1010 System.out.println('~ operand1 = ' + ~operand1); // bitwise XOR // 0101 ^ 0111 operand2 = ' + (operand1 ^ operand2)); // can also be combined with assignment operator to provide shorthand assignment // operand1 = operand1 & operand2 operand1 &= operand2; System.out.println('operand1= ' + operand1); ``` The code demonstrates the use of various bitwise operators, including AND, OR, Complement, and XOR. ## Shift Operators Shift operators in Java are used to shift the bits of a value to the left or right. The following table outlines the shift operators and their descriptions: | Operator Name | Description | | --- | --- | | << (Left Shift) | It shifts x in binary representation y bits to the left, shifting in zeros from the right. | | >> (Right Shift) | It shifts x in binary representation y bits to the right, discarding bits shifted off. | | >>> (Unsigned Right Shift) | It shifts x in binary representation y bits to the right, discarding bits shifted off, and shifting in zeros from the left. | ```java int a = 0x0005; int b = -10; // left shift operator // 0000 0101 << 2 = 0001 0100 System.out.println('a << 2 = ' + (a << 2)); // right shift operator // 0000 0101 >> 2 =0000 0001 // similar to 5 / (2 ^ 2) System.out.println('a >> 2 = ' + (a >> 2)); // unsigned right shift operator System.out.println('b >>> 2 = '+ (b >>> 2)); ``` The code demonstrates the use of left shift, right shift, and unsigned right shift operators. **Type Conversion in Java** Java supports two types of type conversion: Automatic (Widening) and Explicit (Narrowing). ## Automatic Type Conversion Automatic or widening type conversion takes place when two data types are automatically converted. This happens when: The two data types are compatible. When we want to convert a smaller type to the larger type size. java int intVariable = 100; long longVariable = intVariable; float FloatVariable = longVariable; System.out.println('Integer value is : '+intVariable); System.out.println('Long value is : '+longVariable); System.out.println('Float value is : '+FloatVariable); The code demonstrates automatic type conversion from int to long and long to float. ## Documentation Comments Documentation comments are used to generate documentation for the code, and they can include HTML tags and special tags like @author, @param, @return, etc. ```java package JavaCommentsDemo; / ***** ## Find sum of two numbers! *** FindSum program finds the sum** **_and gives the output on_** **the screen. * @author dataflair */ public class FindSum { /** * Method to find average * @param numA- This is the first parameter to calculateSum method * @param numB - This is the second parameter to calculateSum method */ int numA; int numB; FindSum(int numA,int numB) { this.numA=numA; this.numB=numB; } void calculateSum() { System.out.println('Sum of two numbers is '+(numA+numB)); } static class Test { public static void main(String args []) { FindSum obj=new FindSum(10,20); obj.calculateSum(); } } } ``` The code demonstrates the use of documentation comments, including the use of HTML tags and special tags like @author and @param. ## Access Modifiers in Java ## Types of Access Modifiers in Java Java provides four access modifiers to control the visibility of classes, variables, methods, and constructors: **public** : The access level of a public member is not restricted. It can be accessed from anywhere. **protected** : The access level of a protected member is within the same package and all subclasses. Even if the subclass is in a different package, it can access the protected members. **private** : The access level of a private member is only within the class. It is not accessible in the subclass or outside the class. **default** : If you don't use any modifier, it is treated as default by default. The access level of a default member is only within the package. All classes in the same package can access these members. The following table summarizes the access levels provided by the four access modifiers: | Modifier | Class | Package | Subclass | World | |-------------|-------|---------|----------|-------| | public | Y | Y | Y | Y | | protected | Y | Y | Y | N | | default | Y | Y | N | N | | private | Y | N | N | N | ## Examples of Access Modifiers in Java **public** access modifier: java public class PublicClass { public int publicVariable; public void publicMethod() { System.out.println("This is a public method."); } } **protected** access modifier: java protected class ProtectedClass { protected int protectedVariable; protected void protectedMethod() { System.out.println("This is a protected method."); } } **private** access modifier: java class PrivateClass { private int privateVariable; private void privateMethod() { System.out.println("This is a private method."); } } **default** access modifier: java class DefaultClass { int defaultVariable; void defaultMethod() { System.out.println("This is a default method."); } } In the above examples, the PublicClass and its members are accessible from anywhere, the ProtectedClass and its members are accessible within the same package and subclasses, the PrivateClass and its members are accessible only within the class, and the DefaultClass and its members are accessible only within the same package. **Java Access Modifiers** ## Default Access Modifier The default access modifier is used when no access modifier is specified. Classes, methods, and variables with default access modifier are accessible within the same package, but not outside the package. Example: ```java // Java program to illustrate default modifier package JavaAcessModifier; // Class Example is having Default access modifier public class DefaultAcessModifier { void display() { System.out.println("Welcome to the DataFlair's Tutorial of Java!"); } } // Java program to illustrate error while using class from different package with default modifier package JavaAcessModifier1; import JavaAcessModifier.*;