Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
4 views16 pages

Java Consepts

Download as docx, pdf, or txt
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 16

public class Main{

public static void main( String [] args )

Animal dog = new Dog();

Dog d = dog;- --------------------- error because type of (d) not a Animal


in compile time compiler look at dog as Animal not as Dog and execute ( new
Dog(); as run time .)

And maybe Animal reference to other type like Cat .

class Cat extends Animal

class Dog extends Animal

class Animal

Animal can reference to Dog because Dog inheritance from Animal.


import java.util.Random;

public class CompileTimeTypeVsRuntimeType {


public static void main(String[] args) {
Random random = new Random();

double number = random.nextInt(100);


System.out.println(number);
Animal dOrC = (number % 2 == 0) ? new Dog() : new Cat();
System.out.println(dOrC.getClass().getSimpleName());
Dog d = (Dog) dOrC;
}

}
class Animal{

}
class Dog extends Animal{

}
class Cat extends Animal{

value after assignment can know just in runtime not before.

Compiling a program. At first, it might seem that Java is designed to


be best understood by the computer. To the contrary, the language
is designed to be best understood by the programmer (that’s you).
The computer’s language is far more primitive than Java. A compiler
is an application that translates a program from the Java language
to a language more suitable for executing on the computer. The
compiler takes a file with a .java extension as input (your program)
and produces a file with the same name but with a .class extension
(the computer-language version). To use your Java compiler, type in
a terminal window the javac command followed by the file name of
the program you want to compile.

Executing a program. Once you compile the program, you can run it.
This is the exciting part, where your program takes control of your
computer (within the constraints of what the Java system allows). It
is perhaps more accurate to say that your computer follows your
instructions. It is even more accurate to say that a part of the Java
system known as the Java Virtual Machine (the JVM, for short)
directs your computer to follow your instructions. To use the JVM to
execute your program, type the java command followed by the
program name in a terminal window

. A declaration statement associates a variable name with a type at


compile time. Java requires us to use declarations to specify the
names and types of variables. By doing so, we are being explicit
about any computation that we are specifying. Java is said to be a
strongly-typed language, because the Java compiler can check for
consistency at compile time (for example, it does not permit us to
add a String to a double).

Type conversion.

We often find ourselves converting data from one type to another


using one of the following approaches.

 Explicit type conversion. Call methods such


as Math.round(), Integer.parseInt(), and Double.parseDouble().
 Automatic type conversion. For primitive numeric types, the
system automatically performs type conversion when we use a
value whose type has a larger range of values than expected.

Example of Automatic type conversion :


# Integer

num1 = 5 # int

# Float

num2 = 3.2 # float

# Implicit type conversion

result = num1 + num2 # Here, num1 is converted to float

print(result) # Output: 8.2


Explicit casts. Java also has some built-in type conversion methods for
primitive types that you can use when you are aware that you might lose
information, but you have to make your intention using something called
a cast. RandomInt.java reads an integer command-line argument n and prints a
"random" integer between 0 and n−1.

public class RandomInt {


public static void main(String[] args) {
// a positive integer
int n = Integer.parseInt(args[0]);

// a pseudo-random real between 0.0 and 1.0


double r = Math.random();

// a pseudo-random integer between 0 and n-1


int value = (int) (r * n);

System.out.println(value);
}
}

 Automatic conversions for strings. The built-in


type String obeys special rules. One of these special rules is
that you can easily convert any type of data to a String by
using the + operator.
Before assignment is compile time type and after the assignment is
run time type;

Animal dog = new Dog();

Animal dog ----------- compile time type;


new Dog(); ---------- run time type;

Because is that Dog d = dog; is make a compile error because


compiler look at dog as Animal not as a Dog.

A run time error will only occur when the code is actually running. These are the
most difficult - and lead to program crashes and bugs in your code which can be
hard to track down.

An example might be trying to convert a string: "hello" into an integer:

string helloWorld = "hello";


int willThrowRuntimeError = Convert.ToInt32(helloWorld);
The compiler may not see this as a problem but when run an error will be
thrown.

Compiler errors are due to inaccuracies in code, where the compiler throws an
error to alert you to something which will not compile, and therefore cannot be
run.

An example of a compiler error would be:

int = "this is not an int";

Compile-time and Runtime are the two programming terms used in the software
development. Compile-time is the time at which the source code is converted into an
executable code while the run time is the time at which the executable code is started
running. Both the compile-time and runtime refer to different types of error.

Compile-time errors are the errors that occurred when we write the wrong
syntax. If we write the wrong syntax or semantics of any programming
language, then the compile-time errors will be thrown by the compiler. The
compiler will not allow to run the program until all the errors are removed from
the program. When all the errors are removed from the program, then the
compiler will generate the executable file.
The compile-time errors can be:

o Syntax errors

o Semantic errors

The runtime errors are the errors that occur during the execution and
after compilation. The examples of runtime errors are division by zero,
etc. These errors are not easy to detect as the compiler does not point to
these errors.

o Let's explore some typical C runtime error types, cases, and their
possible effects.

Division by Zero

Accessing Array Out of Bounds


Null Pointer Dereference:

A runtime error happens when you try to access a null pointer's


memory address, which is known as dereferencing a null pointer.
Accessing null pointers results in unpredictable behavior because they do
not point to legitimate memory locations.

Example:
int x = 4343434334334; error because compiler can know that this
number is too large.
Int x = int x = Integer.MAX_VALUE + 4; not make any error because
compiler does not know this value after assignment in compile time.

int x = 4L; compile error because (L) indicate that this is long value but
you assignment to int.

Casting with sup and super class:

Row row = getMrgMarriageContractByContractId.first();

if (row instanceof MrgMarriageContractVORowImpl) {

MrgMarriageContractVORowImpl marriageRow =
(MrgMarriageContractVORowImpl) row;

// Safe to use marriageRow here

} else {

// Handle the unexpected type case

The code above is same as

Animal dog = new Dog();

Dog d1 = (Dog) dog;

row is reference to MrgMarriageContractVORowImpl object, but compiler


does not know so we must cast to tell compiler that row is reference to
MrgMarriageContractVORowImpl.

Example of NullPointerException:

NullPointerException in Java occurs when your code attempts to use


an object reference that has not been initialized (i.e., it is null).
1- public class NullPointerExample {

public static void main(String[] args) {

String str = null; // str is null

// Attempting to call a method on a null reference

System.out.println(str.length()); // This will throw


NullPointerException

2- public class Person {


String name;
}

public class NullPointerExample {


public static void main(String[] args) {
Person person = null; // person is null
// Attempting to access a field of a null reference
System.out.println(person.name); // This will throw
NullPointerException
}
}

3- public class NullPointerExample {

public static void main(String[] args) {

int[] numbers = null; // numbers is null

// Attempting to access an index of a null array

System.out.println(numbers[0]); // This will throw


NullPointerException
}

4- public class NullPointerExample {

public static String getName() {

return null; // Method returns null

public static void main(String[] args) {

String name = getName(); // name will be null

// Attempting to use the value returned by the method

System.out.println(name.length()); // This will throw


NullPointerException

Incompatible Types Errors:

Assignment Error:

int myNumber = "Hello"; // Incompatible types: String cannot be con


verted to int.

Return Type Mismatch:

int calculateSum() {

return "Hello"; // Incompatible types: String cannot be converted


to int
}

Method Argument Error

void printNumber(int num) {

System.out.println(num);

printNumber("Hello"); // Incompatible types: String cannot be


converted to int

Array Type Error:

int[] numbers = {1, 2, 3};

String[] names = numbers; // Incompatible types: int[] cannot be


converted to String[]

Different Between Runtype and compile


Type:
In Java an object variable has both a declared
type or compile-time type and a run-time type or actual
type. The( declared type or compile-time type of a variable
is the type that is used in the declaration). (The run-time
type or actual type is the class that actually creates the
object).

The List interface does have an add method so this code


will compile. At run-time the execution environment will
first look for the add method in the Array List class since
that is the actual or run-time type. If it doesn’t find it
there it will look in the parent class and keep looking up at
the inheritance tree till it finds the method. The method
will be found, since otherwise the code would not have
compiled.
List<String> nameList = new ArrayList<String>();
nameList.add("Hi");

The variable message declared below has a declared type


of Object and an actual or run-time type of String. Since
the declared type of message is Object thie code
message.indexOf("h"); will cause a compiler error since
the Object class does not have an indexOf method.
Object message = new String("hi");
message.indexOf("h");

The object is super class.


Any object variable can refer to an object of the declared
type or any descendant (subclass) of the declared type at
run-time. The class String inherits from the class Object so
an Object variable can hold a reference to a String object.
But, you can only call methods that are available in
the Object class unless you cast it back to the String class.

Class class ------


When an object is created, it implicitly contains a
reference to its class. This reference is an instance of the
Class class in Java, which is a built-in class that represents
classes and interfaces in the Java programming language.

Class Reference: Each object retains a reference to its


class, which is essential for method lookup during
execution.

write once, run anywhere:


Allows developers to write code once and have it run in different Platform.

1-compilation to bytecode: where write a java code it first compile to intermediate


form called bytecode.
it’s a low level representation of code that it is not type to any specific platform or
operating system.

To execute the bytecode JVM (Java Virtual Machine) will execute it.

JVM: It’s a software-based execution Environment that interprets and run bytecode.

Each platform like (window, I/OS, It Setra ) has its own JVM implementation.

platform independent bytecode meaning that meaning that the same compile java
program can be executed any platform that has a compatible JVM.

This help the developers to not write the same code in different versions depending
on the platform.
Python Advance:

8.1. Syntax Errors

Syntax errors, also known as parsing errors, are perhaps the most common kind of complaint you get while you are
still learning Python:

The parser repeats the offending line and displays little ‘arrow’s pointing at the token in the line where the error
was detected. The error may be caused by the absence of a token before the indicated token. In the example, the
error is detected at the function print(), since a colon (':') is missing before it. File name and line number are printed
so you know where to look in case the input came from a script.

Exceptions:

Even if a statement or expression is syntactically correct, it may cause an error when an attempt is made to
execute it. Errors detected during execution are called exceptions and are not unconditionally fatal: you will soon
learn how to handle them in Python programs. Most exceptions are not handled by programs, however, and result in
error messages as shown here:
The last line of the error message indicates what happened. Exceptions come in different types, and the type is
printed as part of the message: the types in the example are ZeroDivisionError, NameError and TypeError. The
string printed as the exception type is the name of the built-in exception that occurred. This is true for all built-in
exceptions, but need not be true for user-defined exceptions (although it is a useful convention).

The rest of the line provides detail based on the type of exception and what caused it.

The preceding part of the error message shows the context where the exception occurred, in the form of a stack
traceback. In general, it contains a stack traceback listing source lines; however, it will not display lines read from
standard input.

8.3. Handling Exceptions:

It is possible to write programs that handle selected exceptions. Look at the following example, which asks the user
for input until a valid integer has been entered, but allows the user to interrupt the program (using Control-C or
whatever the operating system supports); note that a user-generated interruption is signaled by raising
the KeyboardInterrupt exception.

The try statement works as follows.

 First, the try clause (the statement(s) between the try and except keywords) is executed.
 If no exception occurs, the except clause is skipped and execution of the try statement is finished.

 If an exception occurs during execution of the try clause, the rest of the clause is skipped. Then, if its type
matches the exception named after the except keyword, the except clause is executed, and then execution
continues after the try/except block.

 If an exception occurs which does not match the exception named in the except clause, it is passed on to
outer try statements; if no handler is found, it is an unhandled exception and execution stops with an error
message.

A try statement may have more than one except clause, to specify handlers for different exceptions. At most one
handler will be executed. Handlers only handle exceptions that occur in the corresponding try clause, not in other
handlers of the same try statement. An except clause may name multiple exceptions as a parenthesized tuple, for

example:

A class in an except clause matches exceptions which are instances of the class itself or one of its derived classes
(but not the other way around — an except clause listing a derived class does not match instances of its base
classes). For example, the following code will print B, C, D in that order:

When an exception occurs, it may have associated values, also known as the exception’s arguments. The presence
and types of the arguments depend on the exception type.

You might also like