Core Java Flashcards
Learning Objectives
To install the JDK using Synaptic
Package Manager.
To run java program, we need to install JDK and Java development kit
Why Java?
Simple Object oriented Platform independent Safe High performance Multi-threaded
Types and applications of Java.
Types and Applications of Java JSP or Java Server Pages Java Applets J2EE or Java Enterprise Edition JavaBeans Mobile Java
Create a simple java program.
class HelloJava { public static void main(String[] args){ System.out.println("My first Java program"); } }
Description :- Public - access modifier, visible to all Static - no need to create object to invoke static method Void - return type. Main - starting point System.out.println - print statement
Naming Conventions in Java
The class name should be in CamelName Example:- PayPal, iPhone, MasterCard.
The method name should be in mixed case
Also method name should be an verb
Example :- showString(), main(),
goToHelp().
Variable name should not begin with digits
We cannot use keywords for class, method and variable name
Example:- Cannot use keywords like
public, private, void, static and many
more.
Install Eclipse on Ubuntu
Install Eclipse on Redhat
fetch software update
-> sudo apt-get update
install software -> sudo apt-get install eclipse Ubuntu - Similar OS Debian Kubuntu & Xubuntu
fetch software list
->sudo yum upate
install software
->sudo yum install eclipse
Redhat - Similar OS
Fedora
Centos
SUSE Linux
—-Introduction to Eclipse—-
What is Eclipse?
Eclipse is a Integrated development environment. One can write, debug and run Ava program with ease
Possible Errors
Missing semicolon Missing double quotes Mis-match file name and class name Typing print statement in lower case
Programming Features Used in
Eclipse IDE
Auto completion
Syntax error highlighting
Error dialog box
Shortcut keys
Data types in Java
There are in total 8 data types defined in Java programming known as the primitive type
Numerical data type
int, float
Arithmetic Operations
Addition : + Subtraction : - Multiplication : * Division : / Modulo Operation(Remainder after division) : %
String Create strings Add strings Convert to lower case Convert to upper case
String in Java, is a sequence of
characters
public class StringDemo { public static void main(String agrs[]){
String greet = "HeLlO"; String name = "JaVa"; char SPACE = ' '; greet = greet.toLowerCase(); name = name.toUpperCase(); String msg = greet + SPACE + name; System.out.println(msg); } }
Output :-
hello JAVA
Type Conversion
Converting one data type to another
Type Conversion
Converting one data type to another
Java facilitates type conversion in two forms:
Implicit (Automatic) Type Conversion
Explicit Type Conversion
Implicit type conversion
Also called as widening conversion because the compiler converts the value of (smaller size) type to the boarder(large size)
byte ——— is convertible to ————-> short, int, long, float, or double
Short ——— is convertible to ————-> int, long, float, or double
char ——— is convertible to ————-> int, long, float, or double
int ——— is convertible to ————-> long, float, or double
long ——— is convertible to ————-> float or double
float ——— is convertible to ————-> double
Explicit type conversion
It is also called as narrowing conversion(narrowing of broader data type to smaller data type). The type casting is done manually by the programmer and not by the compiler
Integer toString(int i) Float toString() Method
Java toString() method is a part of the Integer class of the java.lang package used to convert integer value into String.
Syntax:-
Integer.toString(a)
Java toString() method is a part of the float class if the java.lang package used to convert float value to string
Syntax
a.toString()
Relational operators
Used to check the condition
The size pf boolean data type is 1 bit
It stores only two values(true/false)
Logical operators
They are used to check multiple conditions
and &&
or ||
not !
Conditional Statements
Control the flow of execution of the program
Types:
If : single conditional statement. Executes a block of statements
If-else : Single condition. Executes alternatives statements
if else if : Multiple conditions. Executes various sets of statements. Called as branching or decision making statement
nested if : An if statement inside another if statement
switch
Rules for conditional statement, ternary operator
Add a semicolon for terminating the sentence
Do not add colon after the condition
Add block of code within curly braces
ternary operator : conditional operator providing similar results as if else statement. Short syntax and denoted by ?. Takes three operands at a time.
Syntax :-
Result = Expression ? operand 1 : operand 2
Arrays
Marks: 15, 12, 13, 11, 12, 10
Names: Arun, Bala, David
Temperatures: 33.2, 31.7. 32.3
Rainfall: 25, 31, 29, 13, 27, 3
An array is a collection of similar data types
Array Operations
Arrays.toString
copyOfRange() method
import java.utiil.Arrays;
Arrays.toString
Converts any datatype of of array to string
–> Arrays.toString(var_name)
copyOfRange() method
This method ensures that the continuity of of ranges is maintained. It receives a copy of array from starting index and the ending index of the array
(0,4) implies from index 0 to 3
int[] array = {1,2,3,4,5,6,7};
int[] array1 = Arrays.copyOfRange(array , 3,5);
for(int num : array1)
System.out.println(num);
–> 4,5
Array sort() Array fill() Array copyOf() Arrays.equals()
Array sort() method Sort method of array class. It accepts array and sorts them in ascending order. We can extend this feature by providing start_index and end_index
Arrays.sort(arr);
Array fill() method fill() method of array class. We can assign a particular value to all array elements or in a specified range
Arrays.fill(arr, 5);
Array copyOf() Similar to copyOfRange() method
Arrays.copyOf(arr, 4);
Arrays.equals() array
Compare two array by comparing each elements of the array.
A class in real world A class in Java Structure of a Java Class
- Whatever we can see in the world are all objects
All the object can be categorized into special groups
Each group is termed as class
Example :- class of human being
objects :- different people
Properties :- Eyes, hands, legs
Behaviors: seeing, eating, walking
- Class is a blueprint, from which objects are created
- Set of properties :- variables
set of behaviors :- methods
Members of a class
What is object
Reference Variables
Methods
Fields/Variables
2. Object is instance of class It stores its state in fields/variables It exposes its behavior through methods
- Variables that refer to objects is called as reference variables
Instance Fields
Objects store their individual state in instance fields
They are declared without the static keyword
Non static fields are also known as instance variables or instance fields
Accessing the fields using dot operator
Instance variables are variables that are declare inside a class but outside any method, class Student { String name; int age; }
Java method
It is a collection of statements that performs a specific task
Java constructor
Difference between constructor and method
Constructor is used to initialize instance variables. It is called creation of object. Constructor has the same name as the class name Example:- class Test{ Test(){ //constructor of the body } }
Constructor - no return type
Method - return type
Constructor - it is called using new operator
Method is called using dot operator
Parameterized constructor
A constructor that has parameter is called parametrized constructor. It can have more than one parameter
When we call a parameterized constructor, values are passed to it, they are known as arguments
this keyword
Within the constructor, this is the reference to the current object.
It helps to avoid name conflicts between local variables and instance variables
This is called explicit constructor
invocation.
Non static keyword
When is a non-static block executed?
Any code written between two curly brackets is a non-static block.
When is a non-static block executed? Non-static keyword is executed for each object that is created It executed before the constructor execution It can initialize instance members of the class Any other execution like calculation could also be given in the block
What is Constructor Overloading?
Define multiple constructors for a class.
They must differ in numbers or types of parameters.
What is method overloading
Define two or more methods with same name within a class.
They must differ in number or types of parameters.
These methods are called overloaded methods.
The process is called method overloading.
What is bufferReader?
How to make use of BufferedReader?
Class in Java which is used to read text from input stream
Provides efficient way to read characters, array of characters and lines
Import three classes
- IO exception
- InputStreamReader
- BufferedReader
Syntax:- Syntax I InputStreamReader isr=new InputStreamReader(System.in); BufferedReader br= new BufferedReader(isr);
Subclassing
Private member in subclass
It is a way to create a new class from existing class. The new class created is subclass, child class or derived class The already existing class is called super class or base class or parent class Subclass cannot directly access the private members of the superclass
Superclass
It can have protected or private methods
These methods can access private methods
The subclass can also access private fields through these methods
Method overriding
Annotations
A method in the subclassis said to override the method in the parent class if: name
return type
argument list
matches exactly
Annotations start with at sign character(@) provide data about a program have no direct effect on the operation of the code
Override Annotation If a method is annotated with @Override, compiler generates error if: the method does not override a method declared in its superclass the method signature is different in its superclass
Super keyword
A subclass can use a superclass data or method using the super keyword
The super keyword: refers to the instance variable of the parent class is used to invoke parent class constructor is used to invoke parent class method
What is final keyword?
final is a keyword or reserved word in Java
It can be applied to variables, methods or classes
final variable is
a variable whose value cannot be changed
It will be a constant
final variable as static static final variables cannot be initialized in a constructor. They must be assigned a value with their declaration They must be declared in a static block Static variables are shared among all the objects of a class Creating a new object would change the static variable This is not allowed if the static variable is final
final and private method private methods are not inherited by the child class So we can add a method getDetails() in the child class
What is Polymorphism?
Polymorphism is an ability of an object to take on many forms
Advantages of Polymorphism
Reduction of complexity
Code re-usability
Types of Polymorphism
Compile-time or Method Overloading or Static Binding
Run-time polymorphism or Method Overriding or Dynamic Binding